C#将DataTable数据导出CSV文件
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 }