Reputation: 8747
I am trying to write a function which can create a excel file if not exists. If it exists it should append the contents at the end. The file can grow big so I want to use OPCPackage. Here is the code snippet:
String basePath = "/home/aman/Desktop";
String fileName = "result.xls";
File file = new File(basePath, fileName);
OPCPackage pkg = OPCPackage.openOrCreate(file);
Workbook wb = new XSSFWorkbook(pkg);
Instead of openOrCreate
I tried create()
function also but the error persists. So this leads me to doubt m understanding of open and create function of this package. Here is the question which has information of error occurred.
Upvotes: 1
Views: 7583
Reputation: 1802
We can say that an OPCPackage is related with a xlsx file and a XSSFWorkbook with a OPCPackage respectively.
OpenOrCreate function opens the package related with the file if this package exists or else creates one if it is not (this case rarely occurs). In other words it almost does what Gagravarr wrote without the usage of the f.exists check.
What this function returns is a newly created package if the specified file does not exist, else the package extract from the file.
The usually subsequent processes for your action are:
Upvotes: 0
Reputation: 48336
You're confusing the difference between an OOXML package, and an OOXML file format. A .xlsx
file is built on top of the OOXML package structure, but an empty OOXML package is not a xlsx file.
As an analogy, think of wanting to read a book that's in a bag. You're saying "get the bag, then open it and get out the book" or "get a brand new empty bag, open it, get out the book, oh no there's not book..."
What you probably want to be doing is more like:
Workbook wb;
File f = new File("test.xlsx");
if (f.exists) {
// Existing workbook, open
OPCPackage pkg = OPCPackage.open(f);
wb = new XSSFWorkbook(pkg);
} else {
// Need to create a new, empty workbook
wb = new XSSFWorkbook();
}
Calling new XSSFWorkbook();
creates a brand new, empty workbook to populate. Calling OPCPackage.create()
creates a new empty OPC / OOXML package with nothing in it, which you'd then need to manually populate with an empty XLSX or DOCX structure (which you probably don't normally want to do!)
Upvotes: 6