用NPOI从DataBase到Excel

NPOI的C# Helper代码

 1         public static void WriteExcel(DataTable dt, string filePath)
 2         {
 3             if (!string.IsNullOrEmpty(filePath) && dt.Rows.Count > 0)
 4             {
 5                 HSSFWorkbook wk = new HSSFWorkbook();
 6                 ISheet sheet = wk.CreateSheet(dt.TableName);
 7 
 8                 //列头
 9                 IRow headerRow = sheet.CreateRow(0);
10                 for (int i = 0; i < dt.Columns.Count; i++)
11                 {
12                     headerRow.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
13                 }
14 
15                 //填充内容
16                 for (int i = 0; i < dt.Rows.Count; i++) //注意条件dt.Rows.Count
17                 {
18                     IRow row = sheet.CreateRow(i+1);
19                     for (int j = 0; j < dt.Columns.Count; j++)//注意条件dt.Columns.Count
20                     {
21                         row.CreateCell(j).SetCellValue(Convert.ToString(dt.Rows[i][j])); //注意这里写法
22                     }
23                 }
24                 //写入到客户端
25                 using (MemoryStream ms = new MemoryStream())
26                 {
27                     wk.Write(ms);
28                     using (FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write))
29                     {
30                         byte[] data = ms.ToArray();
31                         file.Write(data,0,data.Length);
32                         file.Flush();
33                     }
34                     wk = null;
35                 }
36 
37             }
38         }
View Code

 

posted @ 2016-12-20 21:49  森林长  阅读(437)  评论(0编辑  收藏  举报