用NPOI从DataBase到Excel '2

2019-05-06 作者:计算机教程   |   浏览(144)

NPOI的C# Helper代码2

 

图片 1图片 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

关键词: