程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 用NPOI從DataBase到Excel,npoidatabaseexcel

用NPOI從DataBase到Excel,npoidatabaseexcel

編輯:C#入門知識

用NPOI從DataBase到Excel,npoidatabaseexcel


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

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved