C# 匯出DataTable至csv檔案

chenpeng0118發表於2014-12-18

有時候將Excel的資料另存到csv檔案會出現csv格式錯誤,以下示例實現將DataTable裡面的資料直接儲存到csv檔案。

 

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


 

相關文章