1
Personal someone would have some example of how to create a web data export on . CSV? I already have one on my system on . XLS, but I need to modify it, someone can 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();
}
csv, is text file... only write... what is the origin of the data ?
– Rovann Linhalis
I made a query pulling the data on my SQL Server in that bring the export
– Leonardo Macedo
Enter the code you’ve already made
– Rovann Linhalis
Take a look in that library, it is able to serialize a class or convert values to CSV.
– gato
@Rovannlinhalis I updated the topic
– Leonardo Macedo
@cat I’ll take a look!
– Leonardo Macedo