Export to Excel using a template in Java
The following example shows how you can create and export new workbooks using an existing Excel workbook as a template.
The procedure is simple:
- load a file,
- fill it in with your data,
- and then save it as a new file.
The example also shows how to use the insertCopy
method for copying an Excel row.
The template row can define the desired styling, number formatting, formulas, etc. When GemBox.Spreadsheet is inserting copied rows, it will automatically adjust the formulas of those rows and also any other formula in the workbook that is affected by that insertion.

import com.gembox.spreadsheet.*;
import java.time.LocalDateTime;
import java.util.Random;
class Program {
public static void main(String[] args) throws java.io.IOException {
// If using Professional version, put your serial key below.
SpreadsheetInfo.setLicense("FREE-LIMITED-KEY");
ExcelFile workbook = ExcelFile.load("%InputFileName%");
int workingDays = %WorkingDays%;
LocalDateTime startDate = LocalDateTime.now().plusDays(-workingDays);
LocalDateTime endDate = LocalDateTime.now();
ExcelWorksheet worksheet = workbook.getWorksheet(0);
// Find cells with placeholder text and set their values.
RowColumn rowColumnPosition;
if ((rowColumnPosition = worksheet.getCells().findText("[Company Name]", true, true)) != null)
worksheet.getCell(rowColumnPosition.getRow(), rowColumnPosition.getColumn()).setValue("ACME Corp");
if ((rowColumnPosition = worksheet.getCells().findText("[Company Address]", true, true)) != null)
worksheet.getCell(rowColumnPosition.getRow(), rowColumnPosition.getColumn()).setValue("240 Old Country Road, Springfield, IL");
if ((rowColumnPosition = worksheet.getCells().findText("[Start Date]", true, true)) != null)
worksheet.getCell(rowColumnPosition.getRow(), rowColumnPosition.getColumn()).setValue(startDate);
if ((rowColumnPosition = worksheet.getCells().findText("[End Date]", true, true)) != null)
worksheet.getCell(rowColumnPosition.getRow(), rowColumnPosition.getColumn()).setValue(endDate);
// Copy template row.
int row = 17;
worksheet.getRows().insertCopy(row + 1, workingDays - 1, worksheet.getRow(row));
// Fill inserted rows with sample data.
Random random = new Random();
for (int i = 0; i < workingDays; i++) {
ExcelRow currentRow = worksheet.getRow(row + i);
currentRow.getCell(1).setValue(startDate.plusDays(i));
currentRow.getCell(2).setValue(random.nextInt(11) + 1);
}
// Calculate formulas in worksheet.
worksheet.calculate();
workbook.save("Template Use.%OutputFileType%");
}
}
Want more?
Like it?
Published: December 13, 2018 | Modified: September 10, 2020 | Author: Marek Turis