C# 导出数据至 CSV

有时候将Excel的数据另存到csv文件会出现csv格式错误,以下示例实现将DataTable里面的数据直接保存到csv文件。

System.Web.HttpRuntime.Cache["v_ds"] = "";

这个v_ds是一个缓存,因为有时候由于页面刷新会清空内存的数据,这里用缓存保存起来,当然还有很多其它的办法。

DataTable dt = (DataTable)System.Web.HttpRuntime.Cache["v_ds"];

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=" + DateTime.Now.ToString("yyyy-MM-dd") + ".csv");
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            Response.ContentType = "application/excel";
            StringBuilder sb = new StringBuilder();
            sb.Append("工单号,栈板号,中箱号,SN,IMEID1,IMEID2,客户PO\r\n");

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                sb.Append("\"" + dt.Rows[i]["工单号"] + "\"" + ",");
                sb.Append("\"" + dt.Rows[i]["栈板号"] + "\"" + ",");
                sb.Append("\"" + dt.Rows[i]["中箱号"] + "\"" + ",");
                sb.Append("\"" + dt.Rows[i]["SN"] + "\"" + ",");
                sb.Append("\"" + dt.Rows[i]["IMEID1"] + "\"" + ",");
                sb.Append("\"" + dt.Rows[i]["IMEID2"] + "\"" + ",");                          
                sb.Append("\"" + dt.Rows[i]["客户PO"] + "\"" + "\r\n");

            }

            Response.Write(sb.ToString());
            Response.End();

 

C# 导出数据至 CSV

上一篇:shell脚本之二:变量的基础知识


下一篇:Windows下查看进程及结束进程命令