Read rows and columns from Excel .xlsx spreadsheets using Apache POI, DataFormatter, and FileInputStream in Java.
In this JavaAnt guide, we cover how to read data from Microsoft Excel (.xlsx) spreadsheets using Apache POI.
Dependencies
To read modern .xlsx workbooks, add the Apache POI OOXML dependencies to your build file:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.3.0</version>
</dependency>Reading Excel Rows and Cells
XSSFWorkbook parses the workbook, XSSFSheet gives access to sheets, and DataFormatter safely extracts text from numeric, date, and string cells.
package com.javaant;
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.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadFromExcel {
private final String filepath;
public ReadFromExcel(String filepath) {
this.filepath = filepath;
}
public Object[][] readDataFromExcel() {
final DataFormatter df = new DataFormatter();
try (FileInputStream file = new FileInputStream(new File(filepath));
XSSFWorkbook workbook = new XSSFWorkbook(file)) {
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
if (!rowIterator.hasNext()) {
return new Object[0][0];
}
// Skip or inspect header row
Row headerRow = rowIterator.next();
int rowCount = sheet.getLastRowNum();
int colCount = headerRow.getPhysicalNumberOfCells();
Object[][] data = new Object[rowCount][colCount];
int rownum = 0;
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
int colnum = 0;
while (cellIterator.hasNext() && colnum < colCount) {
Cell cell = cellIterator.next();
data[rownum][colnum] = df.formatCellValue(cell);
System.out.print(data[rownum][colnum] + " ");
colnum++;
}
rownum++;
System.out.println();
}
return data;
} catch (Exception e) {
e.printStackTrace();
return new Object[0][0];
}
}
public static void main(String[] args) {
ReadFromExcel reader = new ReadFromExcel("sample.xlsx");
reader.readDataFromExcel();
}
}To create styled Excel spreadsheets, see our styling Excel sheets guide and the complete Apache POI tutorial.