How to Write Data from HashMap to Excel using Java in Apache POI?

In this article, let us look at how to write data from HashMap to an excel sheet using Apache POI.

Apache POI library in Java:

ApachePOI is an abbreviation for Poor Obfuscation Implementation, a Java API for reading and writing Microsoft documents. It includes the Wordbook, Sheet, Row, and Cell classes and interfaces. Apache POI may be used to access files with the ‘xlsx’ extension as well as files with the ‘xlsx’ extension.

Apache POI is a free and open-source Java library for creating and manipulating Microsoft Office file formats. The following file formats should be able to be created, modified, and displayed/read using POI. For example, because java does not include built-in support for interacting with Excel files, we must search for open-source APIs to complete the job.

In Java, a HashMap is a form of collection that consists of a key-value pair. Apache POI is an open-source Java library that is used to execute a variety of operations on Microsoft Excel, MS Office, and other applications.

Recommended Reading On: Data Structure notes

Classes Used:

XSSFWorkbook: XSSFWorkbook. It is a class that represents both high-level and low-level Excel file formats. It is part of the org. apache. xssf.

XSSFSheet:

public class XSSFSheet extends POIXMLDocumentPart implements Sheet

It is a High-level representation of a SpreadsheetML worksheet. Sheets are the central structures within a workbook and are where the majority of the spreadsheet work is done. The worksheet, which is displayed as a grid of cells, is the most used type of sheet. Text, numbers, dates, and formulas can all be entered into worksheet cells. Formatting cells is also possible.

FileOutputStream:

FileOutputStream(File file) class creates a file output stream to write to the file provided File object.

FileInputStream:

A FileInputStream reads bytes from a file in the file system. The files that are available are determined by the host environment. FileInputStream is intended for reading raw bytes streams such as image data. Consider using FileReader to read character streams.

Pre-requisites:

We required the following software on your computers to work with these.

  • Check to see if your machine has Java; if not, obtain the most recent Java SDK version from here.
  • Create a Maven project.
  • Add apache poi dependency.

Writing Data from HashMap to Excel using Java in Apache POI

Here we use STS(Spring Tool Suite) to write data from HashMap to an excel sheet

You can either use MyEclipse or STS(SpringToolSuite) for this. Here I am using STS.

STS:

Spring Tool Suite (STS) is a Java IDE designed specifically for the development of Spring-based enterprise applications. It is simpler, quicker, and more convenient. Most notably, it is built on the Eclipse IDE. STS is a free, open-source software platform powered by VMware. Spring Tools 4 represents the next generation of Spring tooling for your preferred development environment. It was largely redesigned from the bottom up to give world-class support for developing Spring-based enterprise apps, regardless of whether you choose Eclipse, Visual Studio Code, or Theia IDE.

Note:

If you are using MyEclipse then create a maven project.

STS directly imports all the classes from maven if we just add dependencies.

Step#1: Open STS(SpringToolSuite) and create a spring stater project say WriteDatafromHashmap in a package com.sheetstips.

Step#2: Add the spring web dependency and click on Finish. Now the project is created successfully.

Step#3: Open the pom.xml file and add the following apache poi dependency from the maven repository.

https://mvnrepository.com/artifact/org.apache.poi/poi

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.12</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.12</version>
</dependency>

Step#4: Create a new class say WritingDataHashmap in the src/main/java folder with the same package com.sheetstips.

Step#5: Write the below code in the above WritingDataHashmap class

Approach:

  • Import all the required libraries using the import keyword
  • Import HashMap library using the import keyword
  • Create a class say WritingDataHashmap
  • Inside the Main driver method, Create a new HSSFWorkbook object.
  • Create a new worksheet in the above workbook object by passing the sheet name as an argument to the createSheet() function(Sheet1 by default).
  • Store it in another variable.
  • Create an HashMap object using the new keyword.
  • Write the data into the above Hashmap object using the put() function.
  • Initialize the row number with 0.
  • Iterate in the entries of the above hashmap using the for loop
  • Get the key of the hashmap entry using the getKey() function and set this value to the excel cell using the setCellValue() function.
  • Here we converted the key to a String
  • Get the value of the hashmap entry key using the getValue() function and set this value to the excel cell using the setCellValue() function
  • Here we converted the value to a String
  • Create an object for the FileOutputStream by passing the output excel file path as an argument to it to place the output file in that location.
  • Write the data which is added in the above steps i.e write the outputFile to the workbook Object using the write() function
  • Close the above-opened output file using the close() function.
  • The Exit of the Program.

Below is the implementation:

package com.sheetstips;

//Import all the required libraries using the import keyword
import java.io.FileOutputStream;
import java.io.IOException;
//Import HashMap library using the import keyword
import java.util.HashMap;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

//Create a class say WritingDataHashmap
public class WritingDataHashmap {

    // Main driver method
    public static void main(String[] args) throws Exception {
        // Create a new HSSFWorkbook object.
        XSSFWorkbook workbookObj = new XSSFWorkbook();
        // Create a new worksheet in the above workbook object by passing
        // the sheet name as an argument to the createSheet() function(Sheet1 by
        // default)
        // Store it in another variable
        XSSFSheet worksheet = workbookObj.createSheet("Data from HashMap");

        // Create an HashMap object using the new keyword.
        HashMap<String, String> mapObj = new HashMap<String, String>();
        // Write the data into the above Hashmap object using the put() function
        mapObj.put("1", "Sheetstips");
        mapObj.put("2", "Btechgeeks");
        mapObj.put("3", "Python-Programs");
        mapObj.put("4", "PythonArrays");

        // Initialize the row number with 0
        int row_number = 0;
        // Iterate in the entries of the above hashmap using the for loop
        for (HashMap.Entry entry : mapObj.entrySet()) {
            XSSFRow row = worksheet.createRow(row_number++);
            // Get the key of the hashmap entry using the getKey() function and set this
            // value to the excel cell using the setCellValue() function
            // Here we converted the key to String
            row.createCell(0).setCellValue((String) entry.getKey());
            // Get the value of the hashmap entry key using the getValue() function and set
            // this value to the excel cell using the setCellValue() function
            // Here we converted the value to String
            row.createCell(1).setCellValue((String) entry.getValue());
        }

        // Create an object for the FileOutputStream by passing the output excel file
        // path as an argument to it to place the output file in that location
        FileOutputStream outputFile = new FileOutputStream("WriteHashMapData.xlsx");
        // Write the data which is added in the above steps i.e
        // write the outputFile to the workbook Object using the write() function
        workbookObj.write(outputFile);
        // Close the above opened outputfile using the close() function
        outputFile.close();
        System.out.println("The Data from the HashMap is written into the Excel File");

    }
}

Step#6: Now run the code by Right-clicking on the project and click on run –> Run as spring boot App

Output:

The Data from the HashMap is written into the Excel File

Write Data From HashMap To Excel

Leave a Comment