Reading Excel with Apache POI

Why Excel

Many clients (banks, insurance) give test data as Excel sheets that business analysts maintain. Apache POI reads .xlsx files from Java.

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>5.3.0</version>
</dependency>
emailpasswordexpected
[email protected]Test@123success
[email protected]wrongInvalid email or password

An Excel Reader

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelReader {
    public static Object[][] read(String path, String sheetName) throws IOException {
        try (InputStream in = new FileInputStream(path); Workbook wb = new XSSFWorkbook(in)) {
            Sheet sheet = wb.getSheet(sheetName);
            DataFormatter fmt = new DataFormatter();          // returns cell text as shown in Excel
            int rows = sheet.getLastRowNum();                  // 0-based, row 0 = header
            int cols = sheet.getRow(0).getLastCellNum();
            Object[][] data = new Object[rows][cols];
            for (int r = 1; r <= rows; r++) {
                Row row = sheet.getRow(r);
                for (int c = 0; c < cols; c++) data[r - 1][c] = fmt.formatCellValue(row.getCell(c));
            }
            return data;
        }
    }
}

@DataProvider(name = "excelLogins")
public Object[][] excelLogins() throws IOException {
    return ExcelReader.read("src/test/resources/testdata/TestData.xlsx", "Login");
}

Note: Use DataFormatter. Reading a numeric cell with getStringCellValue() throws IllegalStateException: Cannot get a STRING value from a NUMERIC cell, and a phone number like 9876543210 comes back as 9.87654321E9 from getNumericCellValue().