如何在客户端PC ASP.net上将Datatable保存为CSV文件

时间:2013-05-16 08:53:41

标签: asp.net csv client-side

如何将数据集作为CSV文件保存到客户端PC?

我可以将文件从服务器保存到客户端PC,我可以将Datatable转换为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();

将datatable转换为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());

3 个答案:

答案 0 :(得分:4)

您使用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();

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

答案 1 :(得分:0)

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

答案 2 :(得分: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();