How to read excel files in java using Apache POI

In this post, we will see how to read excel in java using Apache POI example.

The Apache POI Project's mission 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). In short, you can read and write MS Excel files using Java.

Java Apache POI tutorial:

    Read excel files in java using POI Write excel files in java using POI Working with formula in excel using POI How to set style in excel using POI

Some basics about Apache POI:

There are two prefixes which you encounter while reading/writing excel in java

HSSF: Used for dealing with files excel 2003 or earlier(.xls). Some of classes with HSSF prefix are HSSFWorkbook , HSSFSheet , HSSFRow and HSSFCell.

XSSF: Used for dealing with files excel 2007 or later(.xlsx). Some of classes with XSSF prefix are XSSFWorkbook , XSSFSheet , XSSFRow and XSSFCell.

Here are few classes which you need to aware of.
  • Workbook : This is high level class for representing excel workbook. 
  • Sheet : This is high level class for representing excel sheet. 
  • Row : This is high level class for representing excel row. It has methods which are related to row.
  • Cell: This is high level class for representing individual excel cell. It has methods which are related to cell for example : getDataType().

Dependency:

If you are using maven, then you need to add below dependency in pom.xml.

   org.apache.poi
   poi
   3.13
  
  
   org.apache.poi
   poi-ooxml
   3.13 

If you are not using maven, then you need to add below jars in classpath.
  • poi-3.13.jar
  • commons-codec-1.9.jar
  • poi-ooxml-3.13.jar
  • poi-ooxml-schemas-3.13.jar
  • xmlbeans-2.6.0.jar
  • stax-api-1.0.1.jar

Read excel file using poi:


Java Program:

We are going to read countries.xlsx. Its content is :


Create ReadWriteExcelMain.java as below
package org.arpit.java2blog;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcelMain {

 public static void main(String[] args) throws IOException {
  readFileUsingPOI();
 }

 public static void readFileUsingPOI() throws IOException 
 {
  ClassLoader classLoader = ReadWriteExcelMain.class.getClassLoader();
  String excelFilePath = "Countries.xlsx";
  FileInputStream inputStream = new FileInputStream(new File(classLoader.getResource(excelFilePath).getFile()));

  Workbook workbook = new XSSFWorkbook(inputStream);
  Sheet sheet = workbook.getSheetAt(0);

  Iterator<row> iterator = sheet.iterator();

  while (iterator.hasNext()) {
   Row nextRow = iterator.next();
   Iterator<cell> cellIterator = nextRow.cellIterator();

   while (cellIterator.hasNext()) {
    Cell cell = cellIterator.next();

    switch (cell.getCellType()) {
    case Cell.CELL_TYPE_STRING:
     System.out.print(cell.getStringCellValue());
     break;
    case Cell.CELL_TYPE_NUMERIC:
     System.out.print(cell.getNumericCellValue());
     break;
    case Cell.CELL_TYPE_BOOLEAN:
     System.out.print(cell.getBooleanCellValue());
     break;
    }
    System.out.print(" | ");
   }
   System.out.println();
  }

  workbook.close();
  inputStream.close();
 }


}

When you run above program, you will get following output:
Country | Capital | Population | 
India | Delhi | 10000.0 | 
France | Paris | 40000.0 | 
Germany | Berlin | 20000.0 | 
England | London | 30000.0 | 

Lets be more object oriented. 

We will read each row and create country object. Obviously we will skip header row.
Create a class called Country.java in package com.arpit.java2blog.model
package com.arpit.java2blog.model;

public class Country {

 String name;
 String capital;
 double population;

 //getter and setter methods

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public double getPopulation() {
  return population;
 }

 public void setPopulation(double population) {
  this.population = population;
 }

 public String getCapital() {
  return capital;
 }

 public void setCapital(String capital) {
  this.capital = capital;
 }
 
 public String toString()
 {
  return name+" | "+capital+" | "+population ;
 }

}
ReadExcelWithCounryMain.java

package org.arpit.java2blog;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

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

import com.arpit.java2blog.model.Country;
public class ReadExcelWithCountryMain {

 public static void main(String[] args) throws IOException {
  List<Country> countries=readFileUsingPOI();
  for(Country country:countries)
  {
   System.out.println(country.toString());
  }
 
 }

 public static List<Country> readFileUsingPOI() throws IOException 
 {
  List<Country> countries=new ArrayList<Country>();
  
  ClassLoader classLoader = ReadExcelWithCountryMain.class.getClassLoader();
  String excelFilePath = "Countries.xlsx";
  FileInputStream inputStream = new FileInputStream(new File(classLoader.getResource(excelFilePath).getFile()));

  Workbook workbook = new XSSFWorkbook(inputStream);
  Sheet sheet = workbook.getSheetAt(0);

  Iterator<Row> iterator = sheet.iterator();
    while (iterator.hasNext()) {
   Row nextRow = iterator.next();
   
   // Not creating country object for header
   if(nextRow.getRowNum()==0)
    continue;
   
   Country countryObj=new Country();
   Iterator<Cell> cellIterator = nextRow.cellIterator();
   
   while (cellIterator.hasNext()) {
    Cell cell = cellIterator.next();
    int columnIndex=cell.getColumnIndex();
    switch (columnIndex+1) {
    case 1:
     countryObj.setName(cell.getStringCellValue());
     break;
    case 2:
     countryObj.setCapital(cell.getStringCellValue());
     break;
    case 3:
     countryObj.setPopulation(cell.getNumericCellValue());
     break;
    }
    
   }
   countries.add(countryObj);
   
  }

  workbook.close();
  inputStream.close();
  
  return countries;
 }


}

When you run above program, you will get following output:
India | Delhi | 10000.0
France | Paris | 40000.0
Germany | Berlin | 20000.0
England | London | 30000.0




Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012