用NPOI从DataBase到Excel '2

Posted 森林长

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用NPOI从DataBase到Excel '2相关的知识,希望对你有一定的参考价值。

NPOI的C# Helper代码2

 

 1         public static MemoryStream ExportXls(DataTable dt)
 2         {
 3             HSSFWorkbook wk = new HSSFWorkbook();
 4             ISheet sheet = null;
 5 
 6             string sheetName = "Sheet1";
 7             if (!string.IsNullOrEmpty(dt.TableName))
 8             {
 9                 sheetName = dt.TableName;
10             }
11             sheet = wk.CreateSheet(sheetName);
12             //列头及样式
13             IRow headerRow = sheet.CreateRow(0);
14             ICellStyle headStyle = wk.CreateCellStyle();
15             headStyle.Alignment = HorizontalAlignment.Center;
16 
17             IFont font = wk.CreateFont();
18             font.FontHeightInPoints = 10;
19             font.Boldweight = 700;
20             font.FontName = "微雅黑体";
21             headStyle.SetFont(font);
22             
23             foreach (DataColumn column in dt.Columns)  //column共属性
24             {
25                 headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption); //clomun.ColumnName
26                 headerRow.GetCell(column.Ordinal).CellStyle = headStyle;  //体会
27             }
28 
29             int rowIndex = 1;
30             foreach (DataRow row in dt.Rows)
31             {
32                 //HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex); //也可以这样写  
33                 IRow dataRow = sheet.CreateRow(rowIndex);
34                 foreach (DataColumn column in dt.Columns)
35                 {
36                     dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
37                 }
38                 rowIndex++;
39             }
40             MemoryStream ms = new MemoryStream();
41             wk.Write(ms);
42             ms.Flush();
43             return ms;
44         }
45 
46         //输出
47         public static void SaveToFile(MemoryStream ms) 
48         {
49             using (FileStream fs = File.OpenWrite(@"c:\\1.xls"))
50             {
51                 byte[] data = ms.ToArray();
52                 fs.Write(data,0,data.Length);
53                 fs.Flush();
54                 data = null;
55             }
56         }
57         public static void SaveToFile(MemoryStream ms, string filePath)
58         {
59             using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
60             {
61                 byte[] data = ms.ToArray();
62                 fs.Write(data,0,data.Length);
63                 fs.Flush();
64                 data = null;
65             }
66         }
View Code

 

以上是关于用NPOI从DataBase到Excel '2的主要内容,如果未能解决你的问题,请参考以下文章

NPOI从数据库中导出数据到Excel

C#实现从EXCEL文件读取数据到SqlServer数据库

NPOI导出excel(带图片)

C#用NPOI读取Excel数据到数据库中行的顺序乱怎么办?

比NPOI更好用的Excel操作库——EPPlus

NPOI通过NPOI从内存流中创建EXCEL