poi报空指针,而使用Apache POI空指针异常

I am trying to write a excel file using Apache POI package. Here is the code snippet:

String basePath = "/home/aman/Desktop";

String fileName = "result.xls";

File file = new File(basePath, fileName); //File not null. checked.

OPCPackage pkg = OPCPackage.openOrCreate(file); //pkg not null. checked.

Workbook wb = new XSSFWorkbook(pkg); //GenerateReport.java:63

I get the following error:

Exception in thread "main" java.lang.NullPointerException

at org.apache.poi.POIXMLDocumentPart.read(POIXMLDocumentPart.java:382)

at org.apache.poi.POIXMLDocument.load(POIXMLDocument.java:155)

at org.apache.poi.xssf.usermodel.XSSFWorkbook.(XSSFWorkbook.java:186)

at amazon.category.database.GenerateReport.generateExcel(GenerateReport.java:63)

at amazon.category.database.MerchantAdoptionStats.processAdoptionStats(MerchantAdoptionStats.java:197)

at amazon.category.database.MerchantAdoptionStats.main(MerchantAdoptionStats.java:386)

Any help appreciated.

解决方案

I hit my head against this one for a while myself. The trick is whether or not the file exists prior.

//if file is .xls

Workbook workbook;

if(file.exists) {

NPOIFSFileSystem fs = new NPOIFSFileSystem(file);

workbook = new HSSFWorkbook(fs.getRoot(), false);

}

else {

workbook = new HSSFWorkbook();

}

//if file is .xlsx

Workbook workbook;

if(file.exists) {

OPCPackage pkg = OPCPackage.open(file);

workbook = new XSSFWorkbook(pkg);

}

else {

workbook = new XSSFWorkbook();

}

The trick appears to be (and this doesn't look like it is documented well), that you create the workbooks off of the file system or package objects only if the file exists prior. If you want a new file, then don't use the file system or package objects to create your workbooks.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值