2

如何将数据集作为 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());
4

3 回答 3

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

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

于 2013-05-16T09:02:13.500 回答
0

不要写入 File 对象,而是写入 Response 对象。当你说“Response.End();”时,它会提示保存文件

于 2013-05-16T09:03:04.990 回答
0

你可以试试这个代码,这会创建一个 xls 文件作为附件

    Response.AppendHeader("content-disposition", "attachment;filename=FileEName.xls");
    Response.Charset = "";
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = "application/vnd.ms-excel";
    this.EnableViewState = false;
    Response.Write("PASS YOUR STRING HERE");
    Response.End();
于 2013-05-16T09:55:03.407 回答