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);
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.

Definitions

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

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

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments