C#將DataTable數據導出CSV文件通用方法! //導出按鈕調用導出方法 protected void btnCSV_Click(object sender, EventArgs e) { DataTable dt = ExportData();//獲取datatable數據源 string ...
C#將DataTable數據導出CSV文件通用方法!
//導出按鈕調用導出方法
protected void btnCSV_Click(object sender, EventArgs e)
{
DataTable dt = ExportData();//獲取datatable數據源
string title = "RPT_RC_BILLING_2020_LEOPARD_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".CSV";//導出的文件名
EstablishCSV(dt,title);//將dt數據源和文件名title代入導出方法中
}
1 /// 將DataTable中數據寫入到CSV文件中 2 /// </summary> 3 /// <param name="dt">提供保存數據的DataTable</param> 4 /// <param name="fileName">CSV的文件名</param> 5 private void EstablishCSV(DataTable dt,string fileName) 6 { 7 HttpContext.Current.Response.Clear(); 8 System.IO.StringWriter sw = new System.IO.StringWriter(); 9 int iColCount = dt.Columns.Count; 10 for (int i = 0; i < iColCount; i++)//表頭 11 { 12 sw.Write("\"" + dt.Columns[i] + "\""); 13 if (i < iColCount - 1) 14 { 15 sw.Write(","); 16 } 17 } 18 sw.Write(sw.NewLine); 19 foreach (DataRow dr in dt.Rows)//行內數據 20 { 21 for (int i = 0; i < iColCount; i++) 22 { 23 if (!Convert.IsDBNull(dr[i])) 24 sw.Write("\"" + dr[i].ToString() + "\""); 25 else 26 sw.Write("\"\""); 27 if (i < iColCount - 1) 28 { 29 sw.Write(","); 30 } 31 } 32 sw.Write(sw.NewLine); 33 } 34 sw.Close(); 35 HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename="+ fileName); 36 HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; 37 HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); 38 HttpContext.Current.Response.Write(sw); 39 HttpContext.Current.Response.End(); 40 }導出為CVS文件方法