Using Apache POI to Get or Create a Sheet in Excel Using Java


Apache POI provides a mechanism to work with Excel documents.

However, it has a missing feature when you want to only create a new sheet if one with that name doesn’t already exist.

Luckily, it’s quite simple to get around this using the following code.

List<String> sheets = new ArrayList<>();
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
    Sheet sheet = workbook.getSheetAt(i);
    sheets.add(sheet.getSheetName());
}
Sheet sheet = sheets.contains(name) ?
                workbook.getSheet(name) :
                workbook.createSheet(name);

The code uses the workbook object you pass it, checks to see if a sheet with the specified name exists and then only creates one if needed. Otherwise it returns a reference to the existing one.

Definitions

Our workbook is of type Workbook and is created like this:

Workbook workbook = new XSSFWorkbook();