Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Excel templates with Apache POI

Tags:

Basic question: How do I load an Excel template for use with POI and then save it to an XLS file?

Edit:

The answer is:

FileInputStream inputStream = new FileInputStream(new File(templateFile));
Workbook workbook = new HSSFWorkbook(inputStream);

(Just load the template as a workbook and then write the workbook as an XLS file elsewhere.)

like image 740
Jake Avatar asked Apr 03 '09 14:04

Jake


People also ask

Does Apache POI support XLS?

The Apache POI library supports both . xls and . xlsx files and is a more complex library than other Java libraries for working with Excel files.

Does Apache POI help to read Excel file?

Apache POI is a well-trusted library among many other open-source libraries to handle such usecases involving excel files. Please note that, in addition, we can read and write MS Word and MS PowerPoint files also using the Apache POI library.


2 Answers

Have you tried loading it up as a standard .xls using POI, amending it and then saving it ?

This is the approach I've used for inserting macros in a POI-generated .xls. I create the file with the macro (admittedly as an .xls) and then load it into my app, populate with data and save as a newly-created .xls. That all worked fine.

like image 151
Brian Agnew Avatar answered Sep 29 '22 01:09

Brian Agnew


You can directly load an .xls that will act as the template, and modify it.

POIFSFileSystem fs = new POIFSFileSystem(
                new FileInputStream("template.xls"));
HSSFWorkbook wb = new  HSSFWorkbook(fs, true);

Will load an xls, preserving its structure (macros included). You can then modify it,

HSSFSheet sheet1 = wb.getSheet("Data");
...

and then save it.

FileOutputStream fileOut = new FileOutputStream("new.xls"); 
wb.write(fileOut);
fileOut.close();

Hope this helps.

like image 40
PATRY Guillaume Avatar answered Sep 29 '22 01:09

PATRY Guillaume