How to Write Data from HashMap to Excel using Java in Apache POI?
Apache POI is an open-source java library to create and manipulate various file formats based on Microsoft Office. Using POI, one should be able to perform create, modify and display/read operations on the following file formats. For Example, Java doesn’t provide built-in support for working with excel files, so we need to look for open-source APIs for the job. In this article, we are going to discuss how to write data from HashMap to Excel using the Apache POI library. HashMap is a type of collection in Java that consist of a key-value pair. Apache POI is an open-source java library that is used to perform many operations on Microsoft Excel, MS office, etc.
Let us consider the above diagram as the example of a HashMap containing the key-value pair, we have to read the data from the HashMap and write the key in a column and the value in a separate column.
To work with this example, we need the following in our system:
- Make sure that your system has Java JDK if not installed from here.
- Install the Eclipse IDE from here.
- Create a maven project.
For creating a Maven project refer to this How to Create a Selenium Maven Project with Eclipse to Open Chrome Browser?
- Add the dependency for Apache POI and Apache-ooxml from the MVN repository to the pom.xml file.
- Copy this dependency from the MVN repository and paste them into the POM.xml file
Now we are going to create an Excel file using Apache POI and create a HashMap in java and add the student’s data to the Map. After that, we are going to write the student data from the HashMap to the Excel file. Let’s recreate this example in the coding.
Program for Writing data from HashMap to Excel using Apache POI
- In the initial step, we have to create the workbook and sheet for that workbook.
XSSFWorkbook workbook=new XSSFWorkbook();
- Now create the HashMap and put the data into the Map.
- Declaring the Row number to zero.
- Iterate through the HashMap and create the row.
- Now set the value of the cell, and get the Key and the Value from the HashMap.
- After that create the File output Stream and specify the location for creating the Excel and write the data into it.
After the code is executed, the console print the output as “Data copied to Excel” and an Excel file “Hash.xlsx” is created in the defined location in your system.
Please Login to comment...