标签:style blog http ar io color os sp for
有时候将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();
标签:style blog http ar io color os sp for
原文地址:http://www.cnblogs.com/allen0118/p/4169963.html