How to create a .csv file in asp.net?
asp.net, c#
Solution
Check this: Exporting DataTable to CSV File Format
public void CreateCSVFile(DataTable dt, string strFilePath)
{
#region Export Grid to CSV
// Create the CSV file to which grid data will be exported.
StreamWriter sw = new StreamWriter(strFilePath, false);
// First we will write the headers.
//DataTable dt = m_dsProducts.Tables[0];
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
// Now write all the rows.
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
#endregion
}
If you are trying to force the download to always give a Save As, you should set the content-type to application/octet-stream.
Source:
string attachment = "attachment; filename=MyCsvLol.csv";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AddHeader("Pragma", "public");
var sb = new StringBuilder();
foreach(var line in DataToExportToCSV)
sb.AppendLine(TransformDataLineIntoCsv(line));
HttpContext.Current.Response.Write(sb.ToString());
HttpContext.Current.Response.End();
One of the simplest is using `FileHelpers Library`
FileHelpers.CsvEngine.DataTableToCsv(dataTable, filename);
WriteFile (inherited from FileHelperEngine) Overloaded. Write an array of records to the specified file.
WriteStream (inherited fromFileHelperEngine) Overloaded. Write an array of records to the specified Stream.
WriteString (inherited from FileHelperEngine) Overloaded. Write an array of records to an String and return it.
Reference: Write to CSV file and export it? Export Data to a Comma Delimited (CSV) File for an Application Like Excel export datatable to CSV with Save File Dialog box - C#
Problem
How to Create a .CSV file from the reading the database in asp.net?Can any one suggest me how to create the .CSV file in asp.net? Thanks in Advance.