How to Read Excel File in Java Using Apache POI? - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

How to Read Excel File in Java Using Apache POI?

Share This

In this tutorial, we will discuss how to read content from an MS Excel document with a Java program by using a Java API named Apache POI. It is the most popular Java API to be used to manipulate MS Office files programmatically.

Here we would consider that the excel file contains only one sheet.

Dependencies

You can download the dependency files from here.

After downloading the libraries, you have to add them in JAVA_PATH . Alternatively, you can create an Eclipse project and add them to the project as a library. You are being suggested to add the libraries as an internal library instead of an external library.

If you are not familiar with library linking, follow these steps.

  1. Create a directory, lib , in your project. 
  2. Paste the jars in lib directory. 
  3. Right-click on the project, select Properties, and go to Java Build Path
  4. Click on Add Jars and browse lib directory you have created. It's done!

Source Code to Read from MS Excel

package com.t4b.demo.poi; import java.io.File; import java.io.FileInputStream; import java.util.Iterator; 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; public class ReadExcelDemo { public static void main(String[] args) { try { FileInputStream fileInputStream = new FileInputStream(new File("Demo.xlsx")); XSSFWorkbook xssfWorkbook = new XSSFWorkbook(fileInputStream); XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0); Iterator rowIterator = xssfSheet.iterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); Iterator cellIterator = row.cellIterator(); 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(); } fileInputStream.close(); } catch (Exception e) { e.printStackTrace(); } } }

Explanation of the Code

  • Create an instance of FileInputStream for the Demo.xlsx file.
  • Create an instance of XSSFWorkbook class for the .xlsx file.
  • Create an instance of XSSFSheet. The sheets can be accessed by getSheetAt() method of class XSSFWorkbook, by passing the index of the sheet as an argument.
  • The content of the sheet is read by Iterator over Row.
  • The content of the cells is read by using Iterator over Cell

In case, if you like to know how to write to MS Excel with Java through Apache POI, you can check out this tutorial

Happy Exploring!