如何将数据集作为 CSV 文件保存到客户端电脑?
我可以将文件从服务器保存到客户端电脑,我可以将数据表转换为 CSV 文件,但我似乎无法弄清楚如何将两者放在一起。
将文件从服务器保存到客户端(作为附件)
String FileName = "my file name";
String FilePath = @"C:\testfile.txt";
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath + FileName); //Can only put the file path in here, cant put the datatable or convertion in there..
response.Flush();
response.End();
将数据表转换为 CSV 文件(因为我有一个应保存为 CSV 文件到客户端 PC 的数据表)
StringBuilder sb = new StringBuilder();
string[] columnNames = dt.Columns.Cast<DataColumn>().
Select(column => column.ColumnName).
ToArray();
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in dt.Rows)
{
string[] fields = row.ItemArray.Select(field => field.ToString()).
ToArray();
sb.AppendLine(string.Join(",", fields));
}
File.WriteAllText("test.csv", sb.ToString());