Personal someone would have some example of how to create a web data export in .CSV? I already have one in my system in .XLS, however I need to modify it, can anyone help?
Controller
private void ExportacaoDados(DataSet data, string fileName, int type = 0)
{
if (type == 0)
{
var gv = new GridView();
gv.DataSource = data;
gv.DataBind();
Response.Clear();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".xls");
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
var sw = new StringWriter();
var htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.Close();
Response.End();
}
else
{
var sw = new StringWriter();
sw.Write(ExportToCSVFile(data.Tables[0]));
Response.Clear();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".txt");
Response.ContentType = "text/plain";
Response.Charset = "";
var htw = new HtmlTextWriter(sw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.Close();
Response.End();
}
}
private string ExportToCSVFile(DataTable dtTable)
{
var sbldr = new StringBuilder();
foreach (DataColumn c in dtTable.Columns)
{
sbldr.Append(Regex.Replace(c.ColumnName, @"\n|\t|\r", "") + "|");
}
sbldr.Append("\r\n");
foreach (DataRow row in dtTable.Rows)
{
foreach (DataColumn column in dtTable.Columns)
{
sbldr.Append(Regex.Replace(row[column].ToString(), @"\n|\t|\r", "") + "|");
}
sbldr.AppendLine();
}
return sbldr.ToString();
}