数据导出到Excel中

时间:2021-07-21 20:23:22

自己修改后的一个数据导出到Excel的方法,粘出来与大家共享.

只需要将DataTable要导出的文件的名称输入此方法, 即可.

  1 /// <summary>

 2         /// 将datatable中的数据导出到Excel中
 3         /// </summary>
 4         /// <param name="dt">数据源DataTable</param>
 5         /// <param name="FileName">要导出的文件名</param>       
 6         public static void CreateExcel(DataTable dt, string FileName)
 7         {
 8             // FileName = System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8);
 9             System.Web.HttpContext.Current.Response.Clear();
10             System.Web.HttpContext.Current.Response.Charset = "UTF-8";
11             System.Web.HttpContext.Current.Response.Buffer = true;
12             System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
13             System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition""attachment;filename=\"" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls\"");
14             System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel";
15             string colHeaders = string.Empty;
16             string ls_item = string.Empty;
17             DataRow[] myRow = dt.Select();
18             int i = 0;
19             int cl = dt.Columns.Count;
20             for (int k = 0; k < dt.Columns.Count; k++)
21             {
22                 if (k == (dt.Columns.Count - 1))
23                 {
24                     colHeaders += dt.Columns[k].ToString() + "\n";
25                 }
26                 else
27                 {
28                     colHeaders += dt.Columns[k].ToString() + "\t";
29                 }
30             }
31             System.Web.HttpContext.Current.Response.Output.Write(colHeaders);
32             foreach (DataRow row in myRow)
33             {
34                 for (i = 0; i < cl; i++)
35                 {
36                     if (i == (cl - 1))
37                     {
38                         ls_item += row[i].ToString().Replace("\r\n""").Replace("\r""").Replace("\n""").Replace("\t""") + "\n";
39                     }
40                     else
41                     {
42                         ls_item += row[i].ToString().Replace("\r\n""").Replace("\r""").Replace("\n""").Replace("\t""") + "\t";
43                     }
44                 }
45                 System.Web.HttpContext.Current.Response.Output.Write(ls_item);
46                 ls_item = string.Empty;
47             }
48             System.Web.HttpContext.Current.Response.Output.Flush();
49             System.Web.HttpContext.Current.Response.End();
50 
51         }