So the topic of unreadable content errors in Excel with Apache POI seems common. However, I was surprised that I still could not find an example of my issue, especially since it seems extremely simple what I'm trying to do. This leads me to believe something is probably just going over my head with my understanding of some java objects, specifically File and FileInputStream. I found out through lots of trial and error how to make it work, but my question is WHY one works and why the other does not, and would love to understand the underlying issue. I think it may help others to understand as well. Here's exactly what I'm trying to do:
Open an existing xlsx file, add a sheet to it, and save it to the same file name as its original. In essence, just modify an existing xlsx file to add a sheet.
Below is the code that does not work, and the code that does, and I"m wondering why using the File object does not work. In both examples, I have already created the TravelVouchers.xlsx file with a worksheet named Voucher_1 and it works fine to open it.
The following code leads to a NullPointerException on the travelVouchersWkBk.write(fileOut);
line:
File travelVouchersFile = new File("./Output/TravelVouchers.xlsx");
Workbook travelVouchersWkBk = WorkbookFactory.create(travelVouchersFile);
travelVouchersWkBk.createSheet("Voucher_2");
FileOutputStream fileOut = new FileOutputStream(travelVouchersFile);
travelVouchersWkBk.write(fileOut);
fileOut.flush();
fileOut.close();
While the following code works great:
File travelVouchersFile = new File("./Output/TravelVouchers.xlsx");
FileInputStream fileIn = new FileInputStream(travelVouchersFile);
Workbook travelVouchersWkBk = WorkbookFactory.create(fileIn);
travelVouchersWkBk.createSheet("Voucher_2");
fileIn.close();
FileOutputStream fileOut = new FileOutputStream(travelVouchersFile);
travelVouchersWkBk.write(fileOut);
fileOut.flush();
fileOut.close();
In the code that doesn't work, it causes an error in excel that there is unreadable content, and when I choose to repair, I can open it and it only has Voucher_1. So obviously using WorkbookFactory.create with a File object doesn't work, where using a FileInputStream does, but I'm wondering what I'm not understanding about File vs FileInputStream as it relates to this issue.
Thanks a lot for the clarification, I really appreciate it! Paul