码迷,mamicode.com
首页 > 其他好文 > 详细

使用NPOI随意创建Excel(含下拉列表)

时间:2015-04-13 16:17:12      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

 1   //创建工作簿
 2             HSSFWorkbook ssfworkbook = new HSSFWorkbook();
 3             //创建工作表(页)
 4             HSSFSheet sheet1 = ssfworkbook.CreateSheet("Sheet1");
 5             //创建一行
 6             HSSFRow headerRow = (HSSFRow)sheet1.CreateRow(0);
 7             //设置表头
 8             headerRow.CreateCell(0).SetCellValue("ID");
 9             //设置表头的宽度 
10             sheet1.SetColumnWidth(0, 15 * 256);
11 #region     添加显示下拉列表
12             HSSFSheet sheet2 = ssfworkbook.CreateSheet("ShtDictionary");
13             ssfworkbook.SetSheetHidden(1, true);//隐藏
14             sheet2.CreateRow(0).CreateCell(0).SetCellValue("itemA");//列数据
15             sheet2.CreateRow(1).CreateCell(0).SetCellValue("itemB");
16             sheet2.CreateRow(2).CreateCell(0).SetCellValue("itemC");
17             HSSFName range = ssfworkbook.CreateName();//创建名称
18             range.Reference = "ShtDictionary!$A$1:$A$3";//格式
19             range.NameName = "dicRange";
20             #endregion
21 headerRow.CreateCell(1).SetCellValue("Selected");
22             sheet1.SetColumnWidth(1, 15 * 256);
23             //将下拉列表添加
24             CellRangeAddressList regions = new CellRangeAddressList(1, 65535, 1, 1);
25             DVConstraint constraint = DVConstraint.CreateFormulaListConstraint("dicRange");
26             HSSFDataValidation dataValidate = new HSSFDataValidation(regions, constraint);
27             sheet1.AddValidationData(dataValidate);
28 
29             headerRow.CreateCell(2).SetCellValue("VALUE");
30             sheet1.SetColumnWidth(2, 15 * 256);
31 
32             //写入数据
33             //创建数据行
34             HSSFRow dataRow = (HSSFRow)sheet1.CreateRow(1);
35             //填充数据
36             dataRow.CreateCell(0).SetCellValue("1");//id
37             dataRow.CreateCell(1).SetCellValue("");//选择框
38             dataRow.CreateCell(2).SetCellValue("");//选择框
39        System.IO.MemoryStream ms = new System.IO.MemoryStream();
40             ssfworkbook.Write(ms);
41             string filename = "Sheet1" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + ".xls";
42             Response.AddHeader("Content-Disposition", string.Format("attachment; filename=" + filename + ""));
43             Response.BinaryWrite(ms.ToArray());
44             ms.Close();
45             ms.Dispose();

 

使用NPOI随意创建Excel(含下拉列表)

标签:

原文地址:http://www.cnblogs.com/myblogslh/p/4422203.html

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