Create Excel POI Java
Apache POI is open source java library for reading and writing file in various Microsoft office format such as Excel, Microsoft Word, PowerPoint. Here we will see how to create Excel sheet using Apahce POI. As you might have heard of HSSF and XSSF to read and write spreadsheets and want to know what is the difference between these:
HSSF use to create XLS sheet while XSSF support to create XLSX sheet which is Microsoft new format. Below is and example of both:
- In this example I will show you how to use XSSFWorkbook to create xlsx sheet as both feature are same only extensions are different. Create maven project name: XLSGeneratorUsingPOI below is project structure:
- To use Apache POI you need its jar as mentioned in pom.xml file. I have added log4j jars as well for logging purpose but you don’t need to generate XLSX sheet.
- XLSDataModel.java: Java POJO to store data:
- ExcelGenerator.java: I have made this class as abstract and kept all logic to generate sheet here so that if you have requirement to generate multiple sheets then It will be easy to just extends this class:
- Now to I have created child class: ExcelGeneratorChild which extends ExcelGenerator.java to create XLSX sheet.
- log4j2.xml: This is not needed. If you want to include logger as well in your application you could use it:
- That’s it. Finally java main class CreateXLSSheet.java to generate XLSX sheet:
- Run main class CreateXLSSheet.java as java application. You will see out put on console that XLSX sheet got generated:
- If you want more depth details please visit Apache POI documentation here on its site