This page looks best with JavaScript enabled

Read / Write Excel file in Java using Apache POI

 ·  ☕ 6 min read  ·  ✍️ Dinesh

About a year or two ago I was working with finance team where they wanted to pull the credit card transactions for all the customer using various combinations. Ex –

– Get the credit card txns for today or certain date.

– Get the txns for customer who used Mastercard or Visa.

However they wanted this application to generate a Excel file and save it on their local machine so that they could prepare reports for our CEO. I used a Apache POI project to create jar files. This tutorial will walk you through the process of reading and writing excel sheet. So let’s see – How to read and write excel files in Java?

Brief History on Apache POI

Apache POI is a powerful Java library to work with different Microsoft Office file formats such as Excel, Power point, Visio, MS Word etc. The name POI was originally an acronym for Poor Obfuscation Implementation, referring humorously to the file formats that seemed deliberately obfuscated, but poorly, since they were successfully reverse-engineered.  In short, you can read / write MS Excel files using Java. In addition, you can read/write MS Word and MS PowerPoint files using Java. Apache POI is your Java Excel solution .

Apache POI can be used to create both old ( 2003-2008) and new( 2010 – newer) format. I think the newer jar file to create XLSX document is out of BETA phase now. Back when I used this POI it was still in Beta format.

So let’s see what does it entails to read /write Excel files in Java.

I am will be using Maven and IntelliJ to create my project, however you are welcome to use Eclipse or Netbeans.

Apache POI dependencies

There are two different maven dependencies one for creating an older version of excel – XLS format and other for creating new version of Excel – XLSX format. I am listing both the dependencies here.

<!– For Excel 2007 –>

org.apache.poi

poi

3.9

org.apache.poi

poi-ooxml

3.9

Create a new module in IntelliJ.

Add the dependency in your pom.xml

PAUSE & THINK: KEY POI CLASSES

Before we go ahead here’s quick primer on 3  key classes in POI.

  1. HSSF – Java implementation of the Excel ’97(-2007) file format. e.g. HSSFWorkbookHSSFSheet.
  2. XSSF –  Java implementation of the Excel 2007 OOXML (.xlsx) file format. e.g. XSSFWorkbookXSSFSheet.
  3. SXSSF – Used when very large spreadsheets have to be produced, and heap space is limited. e.g. SXSSFWorkbookSXSSFSheet.

There are other wide range of classes as well which can be used to manipulate the Excel sheet.
Ex – 
 BuiltinFormatsConditionalFormattingRule,ComparisonOperator,CellStyleFontFormatting
IndexedColorsPatternFormattingSheetConditionalFormatting. These used for formatting the sheet and formula evaluation.

HOW TO CREATE A NEW EXCEL SHEET

This involves the following steps.

So go ahead and create a new file called NewExcel.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.dinesh;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * Created by darora on 4/18/14.
 */
public class NewExcel {
    public static void main(String[] args) {
        //Create a new Workbook
        XSSFWorkbook workbook = new XSSFWorkbook();

        //Create a blank sheet
        XSSFSheet sheet = workbook.createSheet("Student data");

        //Create the data for the excel sheet
        Map&lt;string, object[]=""&gt; data = new TreeMap&lt;string, object[]=""&gt;();
        data.put("1", new Object[] {"ID", "FIRSTNAME", "LASTNAME"});
        data.put("2", new Object[] {1, "Randy", "Maven"});
        data.put("3", new Object[] {2, "Raymond", "Smith"});
        data.put("4", new Object[] {3, "Dinesh", "Arora"});
        data.put("5", new Object[] {4, "Barbra", "Klien"});

        //Iterate over data and write it to the sheet
        Set keyset = data.keySet();
        int rownum = 0;
        for (String key : keyset)
        {
            Row row = sheet.createRow(rownum++);
            Object [] objArr = data.get(key);
            int cellnum = 0;
            for (Object obj : objArr)
            {
                Cell cell = row.createCell(cellnum++);
                if(obj instanceof String)
                    cell.setCellValue((String)obj);
                else if(obj instanceof Integer)
                    cell.setCellValue((Integer)obj);
            }
        }
        //Save the excel sheet
        try{
            FileOutputStream out = new FileOutputStream(  
              new File("c:\Dinesh\javahabitExcelDemo.xlsx"));
            workbook.write(out);
            out.close();
            System.out.println("javahabitExcelDemo.xlsx Successfully created");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

OUTPUT

HOW TO READ A NEW EXCEL SHEET

So now that we have written an excel sheet. let’s try to read it back.

The steps involved are

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

package com.dinesh;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;

/**
 * Created by darora on 4/18/14.
 */
public class ReadExcel {
    //Create Workbook instance from excel sheet
    public static void main(String[] args) {
        try {
            //Get the Excel File
            FileInputStream file = new FileInputStream(
              new File("c:\Dinesh\javahabitExcelDemo.xlsx"));
            XSSFWorkbook workbook = new XSSFWorkbook(file);

            //Get the Desired sheet
            XSSFSheet sheet = workbook.getSheetAt(0);

            //Increment over rows
            for (Row row : sheet) {
                //Iterate and get the cells from the row
                Iterator cellIterator = row.cellIterator();
                // Loop till you read all the data
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();

                    switch (cell.getCellType()) {
                        case Cell.CELL_TYPE_NUMERIC:
                            System.out.print(cell.getNumericCellValue() + "t");
                            break;
                        case Cell.CELL_TYPE_STRING:
                            System.out.print(cell.getStringCellValue() + "t");
                            break;
                    }
                }
                System.out.println("");
            }
            file.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

OUTPUT

Using formulas in excel sheet

When working on excel sheets, we sometimes have to create cells which use formulas to calculate their values.  Apache POI has supports methods for adding formula to cells and evaluating the already present formula in the cells. Neat!!

So Let’s see an example on setting a formula cells in the excel sheet.

In this code we will try to calculate the Simple interest. Formula – Principal * Interest * Time.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.dinesh;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by darora on 4/18/14.
 */
public class CalculateFormula {
    public static void main(String[] args)
    {
        //Create the workbook
        XSSFWorkbook workbook = new XSSFWorkbook();
        //Create the sheet
        XSSFSheet sheet = workbook.createSheet("Calculate Simple Interest");
        //Create Wor Headers
        Row header = sheet.createRow(0);
        header.createCell(0).setCellValue("Principal");
        header.createCell(1).setCellValue("Interest");
        header.createCell(2).setCellValue("Time");
        header.createCell(3).setCellValue("OUTPUT (P * r * t)");

        //Create the Rows
        Row dataRow = sheet.createRow(1);
        dataRow.createCell(0).setCellValue(1000d);
        dataRow.createCell(1).setCellValue(12.00);
        dataRow.createCell(2).setCellValue(6d);
        dataRow.createCell(3).setCellFormula("A2*B2*C2");

        //Save the File
        try {
            FileOutputStream out =  new FileOutputStream(  
              new File("c:\Dinesh\javahabitformulaDemo.xlsx"));
            workbook.write(out);
            out.close();
            System.out.println("Excel File with formla is created!");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

OUTPUT

So experiment your way with this jar file and do post your comments and suggestions on topics you had like to see in my future posts.

~ Ciao

Share on
Support the author with

Dinesh Arora
WRITTEN BY
Dinesh
Developer