速度极快的导出excel

 1  public class Export2Excel
 2     {
 3         #region 【导出文件,使用文件流】
 4         /// <summary>
 5         /// 导出文件,使用文件流。该方法使用的数据源为DataTable,导出的Excel文件没有具体的样式。
 6         /// </summary>
 7         /// <param name="dt"></param>
 8         public string ExportToExcel(DataTable dt, string path)
 9         {
10             KillSpecialExcel();
11             string result = string.Empty;
12             try
13             {
14                 // 实例化流对象,以特定的编码向流中写入字符。
15                 StreamWriter sw = new StreamWriter(path, false, Encoding.GetEncoding("gb2312"));
16 
17                 StringBuilder sb = new StringBuilder();
18                 for (int k = 0; k < dt.Columns.Count; k++)
19                 {
20                     // 添加列名称
21                     sb.Append(dt.Columns[k].ColumnName.ToString() + "\t");
22                 }
23                 sb.Append(Environment.NewLine);
24                 // 添加行数据
25                 for (int i = 0; i < dt.Rows.Count; i++)
26                 {
27                     DataRow row = dt.Rows[i];
28                     for (int j = 0; j < dt.Columns.Count; j++)
29                     {
30                         // 根据列数追加行数据
31                         sb.Append(row[j].ToString() + "\t");
32                     }
33                     sb.Append(Environment.NewLine);
34                 }
35                 sw.Write(sb.ToString());
36                 sw.Flush();
37                 sw.Close();
38                 sw.Dispose();
39 
40                 // 导出成功后打开
41                 //System.Diagnostics.Process.Start(path);
42             }
43             catch (Exception)
44             {
45                 result = "请保存或关闭可能已打开的Excel文件";
46             }
47             finally
48             {
49                 dt.Dispose();
50             }
51             return result;
52         }
53         /// <summary>
54         /// 结束进程
55         /// </summary>
56         private static void KillSpecialExcel()
57         {
58             foreach (System.Diagnostics.Process theProc in System.Diagnostics.Process.GetProcessesByName("EXCEL"))
59             {
60                 if (!theProc.HasExited)
61                 {
62                     bool b = theProc.CloseMainWindow();
63                     if (b == false)
64                     {
65                         theProc.Kill();
66                     }
67                     theProc.Close();
68                 }
69             }
70         }
71         #endregion
72     }

 

posted @ 2016-11-17 18:08  DemLiu  阅读(384)  评论(0编辑  收藏  举报