C# Datatable导出Excel方法

C# 导出Excel方法 先引用下System.IO;System.data;

具体函数如下:

 1         public static bool ExportCSV(DataTable dt, string fileNmae)
 2         {
 3             bool Msg = false;
 4             string con = "";
 5             foreach (DataColumn dc in dt.Columns)
 6             {
 7                 con += dc.ColumnName + ",";
 8             }
 9             con = con.TrimEnd(',') + Environment.NewLine;
10 
11             for (int i = 0; i < dt.Rows.Count; i++)
12             {
13                 for (int j = 0; j < dt.Columns.Count; j++)
14                 {
15                     con += dt.Rows[i][j].ToString().Replace("\n", " ").Replace("\r\n", " ").Replace(",", ",") + ",";
16                 }
17                 con = con.TrimEnd(',') + Environment.NewLine;
18             }
19             try
20             {
21                 FileStream fs = new FileStream(fileNmae, FileMode.Create);
22                 byte[] b = Encoding.GetEncoding("gb2312").GetBytes(con);
23                 fs.Write(b, 0, b.Length);
24                 fs.Close();
25                 Msg = true;
26             }
27             catch (Exception ex)
28             {
29                 Log.WriteLog(LogFile.Error, ex.Message);
30             }
31             return Msg;
32         }

手工作品:使用请道明来源: http://www.cnblogs.com/benpao/p/3722161.html