码迷,mamicode.com
首页 > 数据库 > 详细

用NPOI从DataBase到Excel '2

时间:2016-12-20 23:40:46      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:tin   view   files   str   tar   cap   and   ati   excel   

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

标签:tin   view   files   str   tar   cap   and   ati   excel   

原文地址:http://www.cnblogs.com/senlinzhang/p/6204624.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!