将数据表导出到csv并导入到客户端而不保存在服务器中

时间:2014-08-12 21:23:53

标签: c# asp.net csv export

我想将数据导出为csv格式,然后允许用户选择打开/保存到客户端系统。但是csv不应该保存在服务器中。

我使用过这段代码:

this.Response.Clear();
this.Response.ContentType = "application/octet-stream";
this.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + sFileName + "\"");
this.Response.TransmitFile(FilePath);
this.Response.Flush();
this.Response.End();

但这不起作用。

2 个答案:

答案 0 :(得分:0)

正如David建议的那样,只需尝试将CS​​V内容直接传输到响应: -

        Response.Clear();
        Response.AddHeader("content-disposition", "attachment; filename=data.csv");
        Response.ContentType = "text/csv";
        Response.Write(stringContainingCSVData);
        Response.End();

答案 1 :(得分:0)

在DataTable中获取数据并使用此功能。它工作正常。

public void ExportToCSVFile(DataTable dt, string file_name)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition",
         "attachment;filename='" + file_name + "'.csv");
        Response.Charset = "";
        Response.ContentType = "application/text";
        StringBuilder sb = new StringBuilder();
        for (int k = 0; k < dt.Columns.Count; k++)
        {
            sb.Append(dt.Columns[k].ColumnName + ',');
        }
        sb.Append("\r\n");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            for (int k = 0; k < dt.Columns.Count; k++)
            {
                sb.Append(dt.Rows[i][k].ToString() + ',');
            }
            sb.Append("\r\n");
        }
        Response.Output.Write(sb.ToString());
        Response.Flush();
        Response.End();
    }