In this tutorial, I will share with you how to read Excel files programmatically using Java.

You know, Excel is the very popular file format created by Microsoft. Although it is not an opened file format, Java applications can still read and write Excel files using the Apache POI - the Java API for Microsoft Documents, because the development team uses reverse-engineering to understand the Excel file format. Hence the name POI stands for Poor Obfuscation Implementation.

This tutorial shows you how simple and easy it is to read Excel files using Apache POI’s API.

 

1. Getting Apache POI library

Apache POI is the pure Java API for reading and writing Excel files in both formats XLS (Excel 2003 and earlier) and XLSX (Excel 2007 and later). To use Apache POI in your Java project:

 

2. The Apache POI API Basics

There are two main prefixes which you will encounter when working with Apache POI:

And to get started the Apache POI API, you just need to understand and use the following 4 interfaces:

Now, let’s walk through some real-life examples.

 

3. Reading from Excel File Examples

Suppose you want to read an Excel file whose content looks like the following screenshot:

Books Excel File

This spreadsheet contains information about books (title, author and price).

 

A Simple Example to Read Excel File in Java

Here’s a dirty example that reads every cell in the first sheet of the workbook and prints out values in every cell, row by row:

package net.codejava.excel;

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;

/**
 * A dirty simple program that reads an Excel file.
 * @author www.codejava.net
 *
 */
public class SimpleExcelReaderExample {
	
	public static void main(String[] args) throws IOException {
		String excelFilePath = "Books.xlsx";
		FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
		
		Workbook workbook = new XSSFWorkbook(inputStream);
		Sheet firstSheet = workbook.getSheetAt(0);
		Iterator<Row> iterator = firstSheet.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_BOOLEAN:
						System.out.print(cell.getBooleanCellValue());
						break;
					case Cell.CELL_TYPE_NUMERIC:
						System.out.print(cell.getNumericCellValue());
						break;
				}
				System.out.print(" - ");
			}
			System.out.println();
		}
		
		workbook.close();
		inputStream.close();
	}

}
Output:

Head First Java - Kathy Serria - 79.0 -
Effective Java - Joshua Bloch - 36.0 -
Clean Code - Robert Martin - 42.0 -
Thinking in Java - Bruce Eckel - 35.0 -
 

A More Object-Oriented Example to read Excel File

For nicer and more object-oriented program, let’s create a model class (Book.java) with the following code:

package net.codejava.excel;

public class Book {
	private String title;
	private String author;
	private float price;

	public Book() {
	}

	public String toString() {
		return String.format("%s - %s - %f", title, author, price);
	}

	// getters and setters
}
Write a method that reads value of a cell as following:

private Object getCellValue(Cell cell) {
	switch (cell.getCellType()) {
	case Cell.CELL_TYPE_STRING:
		return cell.getStringCellValue();

	case Cell.CELL_TYPE_BOOLEAN:
		return cell.getBooleanCellValue();

	case Cell.CELL_TYPE_NUMERIC:
		return cell.getNumericCellValue();
	}

	return null;
}
Next, implement a method that reads an Excel file and returns a list of books:

public List<Book> readBooksFromExcelFile(String excelFilePath) throws IOException {
	List<Book> listBooks = new ArrayList<>();
	FileInputStream inputStream = new FileInputStream(new File(excelFilePath));

	Workbook workbook = new XSSFWorkbook(inputStream);
	Sheet firstSheet = workbook.getSheetAt(0);
	Iterator<Row> iterator = firstSheet.iterator();

	while (iterator.hasNext()) {
		Row nextRow = iterator.next();
		Iterator<Cell> cellIterator = nextRow.cellIterator();
		Book aBook = new Book();

		while (cellIterator.hasNext()) {
			Cell nextCell = cellIterator.next();
			int columnIndex = nextCell.getColumnIndex();

			switch (columnIndex) {
			case 1:
				aBook.setTitle((String) getCellValue(nextCell));
				break;
			case 2:
				aBook.setAuthor((String) getCellValue(nextCell));
				break;
			case 3:
				aBook.setPrice((double) getCellValue(nextCell));
				break;
			}


		}
		listBooks.add(aBook);
	}

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

	return listBooks;
}
And here is the testing code:

public static void main(String[] args) throws IOException {
	String excelFilePath = "Books.xlsx";
	ExcelReaderExample2 reader = new ExcelReaderExample2();
	List<Book> listBooks = reader.readBooksFromExcelFile(excelFilePath);
	System.out.println(listBooks);
}
Output:

[Head First Java - Kathy Serria - 79.000000, Effective Java - Joshua Bloch - 36.000000,
	Clean Code - Robert Martin - 42.000000, Thinking in Java - Bruce Eckel - 35.000000]
 

How to Read both Excel 2003 and 2007 format in Java

For better supporting both users using Excel 2003 and 2007, it’s recommended to write a separate factory method that returns an XSSFWorkbookor HSSFWorkbookdepending on the file extension of the file (.xls or .xlsx):

private Workbook getWorkbook(FileInputStream inputStream, String excelFilePath)
		throws IOException {
	Workbook workbook = null;

	if (excelFilePath.endsWith("xlsx")) {
		workbook = new XSSFWorkbook(inputStream);
	} else if (excelFilePath.endsWith("xls")) {
		workbook = new HSSFWorkbook(inputStream);
	} else {
		throw new IllegalArgumentException("The specified file is not Excel file");
	}

	return workbook;
}
And here’s a usage example of this factory method:

String excelFilePath = "Books.xlsx"; // can be .xls or .xlsx

FileInputStream inputStream = new FileInputStream(new File(excelFilePath));

Workbook workbook = getWorkbook(inputStream, excelFilePath);
 

Reading Other Information

That's how to read Excel files in Java programmatically. I recommend you to take this Java course to fully learn Java programming.

 

Related Java Excel Tutorials:

 

References:

 


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Attachments:
Download this file (ExcelFileReaderExamples.zip)ExcelFileReaderExamples.zip[Excel Files Reader Java Code Examples]15 kB