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

0 min read 127 words

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();
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts