Commonly it’s necessary to manage Microsoft Excel files from Java applications. It can be usefull, for example, to export / import data, report generation, etc. Apache POI is a library from Apache fundation, which has become a de facto standard for this type of tasks. In this article we will see an example of how to generate a simple excel file with Apache POI.
Add project dependency
Using a Maven project, we can add the POI dependency like this:
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.12-beta1</version>
</dependency>
</dependencies>
If we are not using Maven, we have to download the library from here and add it manually to our project.
Excel Format
As we can see on its website, apache POI give us two APIs:
- HSSF: it allows to generate files compatible with MS Office 97
- XSSF: it allows to generate files compatible with MS Office 2007
In this case, to generate files with maximum compatibility, we use the API HSSF.
Generating the Excel book
The way to work with Apache POI will be always the same:
- Create a workbook
- Create sheets in the workbook
- Create rows in the sheets
- Create cells in the rows
- Set content for cells
Let’s see how to do that in Java code:
1. Create the workbook:
HSSFWorkbook workbook = new HSSFWorkbook(); |
2. Create a sheet:
HSSFSheet sheet = workbook.createSheet("My Sheet"); |
3. Create a row:
HSSFRow row = sheet.createRow(0); |
4. Create a cell:
HSSFCell cell = row.createCell(0); |
5. Set cell’s content:
cell.setCellValue("Hello, World!"); |
Save the generated Excel
We can save the generated excel in a file by passing to it the output stream:
OutputStream out = new FileOutputStream("src/main/resources/SimpleExcel.xls"); workbook.write(out); |
Source code
You can download the source code used in this article from my GitHub repository, project Poi-SimpleExcelGenerator.
More information
Apache POI allows to set styles, formulas, formats, etc. to the generated content. I will cover this topics on later articles. Meanwhile, you can get all information from the official documentation.