通常我们使用NPOI操作excel的时候会先初始化一个IWorkbook的对象HSSFWorkbook,方法如下:
using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))
{
return new HSSFWorkbook(file);
}
但是这种方法这能操作2007以及低版本的excel,操作07以上版本则会出现错误:
The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF)
想要操作高版本的excel则需要使用XSSFWorkbook,所以为了兼容所有版本的excel,通用的方法如下:
using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))
{
try
{
return new XSSFWorkbook(file);
}
catch (Exception ex)
{
return new HSSFWorkbook(file);
}
}
同时使用这种方法也必须注意,XSSFWorkbook和HSSFWorkbook的位置不能互换,也就是说必须先使用XSSFWorkbook初始化,如果失败,再使用HSSFWorkbook初始化,否则也会出现错误:
“无法访问已关闭的文件。”
附上excel的操作类库:
http://download.youkuaiyun.com/download/xiaoguidangjiajia/9381595