Aspose.Cell和NPOI生成Excel文件2

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);

5.NPOP打印设置

NPOI打印设置:FitToPage 设置为 true,FitHeight 设置为 1,FitWidth设置为1,即可在打印时讲内容打印到一页。

//XSSFWorkbook 版本下创建的 Sheet
sheet.FitToPage = true;
sheet.PrintSetup.FitHeight = 1;
sheet.PrintSetup.FitWidth = 1;

//HSSFWorkbook 版本下,此版本未测试
sheet.SetFitToPage(true);
sheet.SetPrintScale(100); //设置打印比例

 

posted @ 2017-06-30 11:27  BOBO~  阅读(1409)  评论(0编辑  收藏  举报