You can create a XLS file from a XLS template.
But, to do this, you need to create a copy of the template every time you need to use the template. If not, you will edit the original template (what you not want).
So, you need first get your template file:
URL url = Thread.currentThread().getContextClassLoader().getResource("templates/template.xls");
File file = new File(url.getPath());
Copy the template file:
try (FileOutputStream fileOutputStream = new FileOutputStream("/home/jake/fileCopiedFromTemplate.xls")) {
Files.copy(file.toPath(), fileOutputStream);
Workbook workbook = new HSSFWorkbook();
workbook.write(fileOutputStream);
}
Access the new copied file:
FileInputStream inp = new FileInputStream("/home/jake/fileCopiedFromTemplate.xls");
Create a Workbook
, so you can write in your new file:
Workbook workbook = WorkbookFactory.create(inp);
After write in your workbook:
try (FileOutputStream fileOut = new FileOutputStream("/home/jake/fileCopiedFromTemplate.xls")) {
workbook.write(fileOut);
}
A tip to create a XLS template file is mark the template with some variable for you localize the position that you would like to fill. Like:
------------------------------------
| | Columna A | Column B |
------------------------------------
| 1 | Some description |
------------------------------------
| 2 | {person.name} | {person.age} |
------------------------------------