- 推荐使用2.0版本,虽然是beta版,但是至少支持office2007以上xlsx等后缀的文件。当让,需要做好文档不全的心理准备
- xls后缀文件使用HSSF包,xlsx使用XSSF包。ex,xlsx格式文件,实例化,IWorkbook exportFile = new XSSFWorkbook(templatePath);
- demo大部分使用CreateRow,CreateCell等方法,但是,这些方法是重新实例化,会覆盖原有的单元格和列的属性,比如背景色。请改用GetRow和GetCell方法。
- Workbook实例化(读取现有excel模板等)消耗的时间可能会比较慢,也可能和我电脑配置渣有关。
- 单元格赋值的时候最好使用ToString()方式字符串赋值,因为时间等类型不会自动转换。
- 相比较而言,使用NPOI方式不需要服务器安装office,不需要配置安全属性,但是,个人还是更加喜欢用Office组件,因为更加完善。
参考
demo
bool
ifSuccess =
false
;
string
msg =
""
;
string
templatePath = Server.MapPath(
"\\Content\\template\\temp.xlsx"
);
string
resultPath =
""
;
try
{
resultPath =
"\\Content\\template\\"
+ lCode +
"_"
+
DateTime
.Now.Second +
".xlsx"
;
string
savePath = Server.MapPath(resultPath);
IWorkbook
exportFile =
new
XSSFWorkbook
(templatePath);
ISheet
sheet1 = exportFile.GetSheet(
"SheetName"
);
//int x = 1;
//for (int i = 1; i <= 15; i++)
//{
// IRow row = sheet1.CreateRow(i);
// for (int j = 0; j < 15; j++)
// {
// row.CreateCell(j).SetCellValue((x++).ToString());
// }
//}
IRow
row = sheet1.CreateRow(3);
row.CreateCell(0).SetCellValue("123");
sheet1.GetRow(1).GetCell(1).SetCellValue(
DateTime
.Now.ToString()
);
FileStream
sw = System.IO.
File
.Create(savePath);
exportFile.Write(sw);
sw.Close();
ifSuccess =
true
;
}
catch
(
Exception
e)
{
msg = e.Message;
if
(e.InnerException !=
null
)
msg += e.InnerException.Message;
}