码迷,mamicode.com
首页 > Web开发 > 详细

Aspose.Cell和NPOI生成Excel文件2

时间:2017-06-30 12:19:31      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:name   etc   tar   work   exce   oct   table   clear   cte   

NPOI还是比较好用的,引用dll程序集即可

1创建workbook和工作流

HSSFWorkbook workbook = new HSSFWorkbook();
MemoryStream ms = new MemoryStream();

2这里是一个多sheet的例子,可以通过循环一个个生成

 1 List<DataTable> listtable = new List<DataTable>();
 2 for(int t = 1; t < = listtable.Count();t++)
 3 {
 4      DataTable tempTable = listtable[t-1];
 5      //增加sheet,listname是一个List<string>作为表明
 6      HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet(listname[t-1]);    
 7      HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0);
 8      foreach(DataColumn column in tempTable.Columns)
 9      {
10           //创建列
11           headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
12      }
13      int rowIndex = 1;
14      foreach(DataRow row in tempTable.Rows)
15      {
16           //创建行
17           HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex);   
18           foreach(DataColumn column in tempTable.Columns)
19           {
20                dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
21           }
22           rowIndex++;
23      }
24 }        

3工作中的sheet都创建好之后,写入流

workbook.Write(ms);

4最后返回给浏览器端

byte[] strmByte = ms.ToArray();
ms.Dispose();
Response.ClearContent();
Response.ContentEncoding =  System.Text.Encoding.UTF8;
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition","attachment;fileName="+"name.xlsx");
Response.BinaryWrite(strmByte);

 

Aspose.Cell和NPOI生成Excel文件2

标签:name   etc   tar   work   exce   oct   table   clear   cte   

原文地址:http://www.cnblogs.com/pocn/p/7098048.html

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