您的位置:首页 > 其它

关于使用NPOI2.0 进行Excel导出的一些笔记

2013-12-05 09:00 369 查看
推荐使用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组件,因为更加完善。

参考
http://tonyqus.sinaapp.com/npoi2tutorial

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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: