检查这个: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
}
如果您尝试强制下载始终提供另存为,则应将内容类型设置为 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 正在使用FileHelpers Library
FileHelpers.CsvEngine.DataTableToCsv(dataTable, filename);
WriteFile(继承自 FileHelperEngine)重载。写一个数组
记录到指定文件。
WriteStream(继承自FileHelperEngine)已重载。将记录数组写入
指定的流。
WriteString(继承自
FileHelperEngine)重载。将记录数组写入字符串
并返回它。
参考:
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#