Skip to content

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 = ; i < workbook.getNumberOfSheets(); i++) { Sheet sheet = workbook.getSheetAt(i); sheets.add(sheet.getSheetName()); } Sheet sheet = sheets.contains(name) ? workbook.getSheet(name) : workbook.createSheet(name);
Code language: Java (java)

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.


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

Workbook workbook = new XSSFWorkbook();
Code language: Java (java)

See also  How to Solve the Maximize Distance to Closest Person Challenge in Java
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x