如何在客户端 PC ASP.net 上将数据表另存为 CSV 文件

Rua*_*uan 2 csv asp.net client-side

如何将数据集作为 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();
Run Code Online (Sandbox Code Playgroud)

将数据表转换为 CSV 文件(因为我有一个应作为 CSV 文件保存到客户端电脑的数据表)

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());
Run Code Online (Sandbox Code Playgroud)

Ari*_*tos 5

您使用response.Write(sb.ToString());而非response.TransmitFile来呈现您的 CSV 生成数据的输出。例如:

response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=DownloadedData.txt;");

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));
}

// the most easy way as you have type it
response.Write(sb.ToString());


response.Flush();
response.End();
Run Code Online (Sandbox Code Playgroud)

并且最好使用处理程序,而不是从页面执行此操作。