Generic way of writing data in excel using apache poi

The example is about generic way of writing data in excel using apache poi. With this example I will show you how to create an excel file and write any kind of list of objects to excel file using Apache POI in Java language.

The Apache POI is to create and maintain Java APIs for manipulating various file formats based upon the Office Open XML standards (OOXML) and Microsoft’s OLE 2 Compound Document format (OLE2). You can read and write MS Excel files using Java. In addition, you can read and write MS Word and MS PowerPoint files using Java. Apache POI is the Java Excel solution (for Excel 97-2008).

If you already have an idea on how to create a maven project in Eclipse will be great otherwise I will tell you here how to create a maven project in Eclipse.

Now we will see the below steps how to create a maven based spring project in Eclipse.

Step 1. Create a standalone maven project in Eclipse.

Go to File -> New -> Other. On popup window under Maven select Maven Project. Then click on Next. Select the workspace location – either default or browse the location. Click on Next. Now in next window select the row as highlighted from the below list of archtypes and click on Next button.

maven-arctype-quickstart

Now enter the required fields (Group Id, Artifact Id) as shown below.

Group Id : com.roytuts
Artifact Id : java

Step 2. Modify the pom.xml file as shown below. Notice we have added only single dependency for apache poi.

Step 4. Create a generic method to handle any kind of data to excel through single method. We create a file object first. Then we have created excel workbook and finally create a sheet on the workbook. We retrieve the attribute names from the class object, for example, Person class. Then we find the getter methods from the class and finally write the value from all getter methods to the excel sheet.

Step 5. Create a junit test case to test the above class whether it writes to the excel file or not. In the below junit class we first setup few dummy data before the actual test to be executed. Then we write the excel file with those dummy data into D drive in Windows OS. This class shows generic way of writing data in excel using apache poi.