It’s always interesting to be able to generate Microsoft Excel XLSX files in an application to propose reports to users for example. In that tutorial, you are going to learn how to generate Microsoft Excel files in a Java application.
For that, we are going to use the great Apache POI API available just there : https://poi.apache.org/download.html
Note that you can watch this tutorial as a video on YouTube :
Adding Apache POI as a dependency
First step is to add Apache POI as a Maven dependency in the build file of our Java project :
We have chosen to generate Excel XLSX files in that tutorial but the logic is the same to generate Excel XLS older file format. So, we have added both dependencies in our Maven POM but just the poi-ooxml is needed for our example.
Creating a Contact POJO
In our example, we are going to generate an Excel file containing a list of contacts. So, we create a Contact POJO object to represent the contacts as a Java object :
Like you can see, a Contact will have a first name, a last name, an email and a date of birth.
Creating the Excel file with the Contacts data
With the Apache POI API, an Excel file is represented by a Workbook object. Like we want to generate a XLSX file, we need to create a XSSFWorkbook instance. For a XLS file, we would need to create a HSSFWorkbook instance. Once the Workbook instance is created, we need to create a new Sheet object by calling the createSheet method of the Workbook object :
In our generated file, we will have a row header with a specific style. For that, we create a Font object by calling the createFont method of the Workbook instance. Then, we define the color and the size of our Font. Next step is to associate this font to a CellStyle object created by calling the createCellStyle method of the Workbook instance like that :
Now, we must create the header row. We set the title for each cell and also the specific cell style created. Note that the title for each cell of the row header come from a static array defined as a property of our ExcelWriter class :
Then, we create other rows and cells with contacts’ data by iterating on the list of contacts. Besides, we resize all columns of our file to fit the content size :
Generating the Excel file
Finally, we have to generate the Excel file by writing the content of our Workbook instance to a file. For that, we create a FileOutputStream instance with the name for our file and then we pass this instance as a parameter of the write method of the Workbook object :
Complete source code of our ExcelWriter class
The complete source code of our ExcelWriter class is available just below :
By executing the ExcelWriter class on a JVM, the contacts.xlsx file should be generated on your machine and you should have the following result :
That’s all for that tutorial. Don’t hesitate to visit the SSaurel’s Blog to discover more tutorials on Java and Android development : https://www.ssaurel.com/blog
You can also visit the SSaurel’s Channel :