Wednesday, December 2, 2026

Reading and Writing Data to Excel File in Java using Apache POI

Reading and Writing Data to Excel File in Java using Apache POI

In Java, you can use a for loop to read Excel data, write data into Excel, and iterate through rows and columns.

The commonly used library is Apache POI.

Reading and Writing Data to Excel File in Java using Apache POI


1. Add Apache POI Dependency

For Maven, add the following dependency to your pom.xml file:

<dependencies>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.4.1</version>
    </dependency>
</dependencies>

2. Read Excel Using For Loop in Java

Suppose your Excel file (Employee.xlsx) contains the following data:

ID Name Salary
101 Sumit 50000
102 Rahul 60000
103 Amit 70000

Java Code

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

import java.io.FileInputStream;

public class ReadExcel {

    public static void main(String[] args) throws Exception {

        FileInputStream fis =
            new FileInputStream("Employee.xlsx");

        Workbook workbook = new XSSFWorkbook(fis);

        Sheet sheet = workbook.getSheetAt(0);

        // Iterate rows
        for (int i = 0; i <= sheet.getLastRowNum(); i++) {

            Row row = sheet.getRow(i);

            if (row == null) {
                continue;
            }

            // Iterate columns
            for (int j = 0; j < row.getLastCellNum(); j++) {

                Cell cell = row.getCell(j);

                if (cell != null) {
                    System.out.print(
                        cell.toString() + " | "
                    );
                }
            }

            System.out.println();
        }

        workbook.close();
        fis.close();
    }
}

Output

101 | Sumit | 50000.0 |
102 | Rahul | 60000.0 |
103 | Amit | 70000.0 |

3. Read Excel Using Nested For Loops

Understanding the two loops:

for (int i = 0; i <= sheet.getLastRowNum(); i++) {

    Row row = sheet.getRow(i);

    for (int j = 0; j < row.getLastCellNum(); j++) {

        Cell cell = row.getCell(j);

        System.out.println(cell);
    }
}
  • Outer loop (i): Iterates through Excel rows.
  • Inner loop (j): Iterates through Excel columns.
  • getLastRowNum(): Returns the last row index.
  • getLastCellNum(): Returns the last cell index plus one.

4. Write Data into Excel Using For Loop

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

import java.io.FileOutputStream;

public class WriteExcel {

    public static void main(String[] args) throws Exception {

        Workbook workbook = new XSSFWorkbook();

        Sheet sheet = workbook.createSheet("Employee");

        Object[][] data = {
            {"ID", "Name", "Salary"},
            {101, "Sumit", 50000},
            {102, "Rahul", 60000},
            {103, "Amit", 70000}
        };

        for (int i = 0; i < data.length; i++) {

            Row row = sheet.createRow(i);

            for (int j = 0; j < data[i].length; j++) {

                Cell cell = row.createCell(j);

                Object value = data[i][j];

                if (value instanceof String) {
                    cell.setCellValue((String) value);
                } else if (value instanceof Number) {
                    cell.setCellValue(
                        ((Number) value).doubleValue()
                    );
                }
            }
        }

        try (FileOutputStream fos =
                 new FileOutputStream("Employee.xlsx")) {

            workbook.write(fos);
        }

        workbook.close();

        System.out.println("Excel file created successfully!");
    }
}

Output

Excel file created successfully!

The generated Employee.xlsx file contains:

ID Name Salary
101 Sumit 50000
102 Rahul 60000
103 Amit 70000

5. Important Apache POI Methods

Method Description
new XSSFWorkbook() Create Excel workbook.
getSheetAt(0) Get first sheet.
getSheet("Sheet1") Get sheet by name.
getLastRowNum() Get last row index.
getRow(i) Get particular row.
getCell(j) Get particular cell.
getStringCellValue() Read string value.
getNumericCellValue() Read numeric value.
createRow(i) Create row.
createCell(j) Create cell.
setCellValue() Write cell value.

6. QA Automation Interview Example

In Selenium or Playwright automation, Excel is commonly used for data-driven testing.

Example:

for (int i = 1; i <= sheet.getLastRowNum(); i++) {

    String username = sheet.getRow(i)
                           .getCell(0)
                           .getStringCellValue();

    String password = sheet.getRow(i)
                           .getCell(1)
                           .getStringCellValue();

    driver.findElement(By.id("username"))
          .sendKeys(username);

    driver.findElement(By.id("password"))
          .sendKeys(password);

    driver.findElement(By.id("login")).click();
}

Example Excel Test Data

Username Password
user1 pass123
user2 pass456
user3 pass789

Each iteration executes the login test with a different set of credentials.



Using instanceof Integer and Double

if (value instanceof Integer) {
    cell.setCellValue((Integer) value);
} else if (value instanceof Double) {
    cell.setCellValue((Double) value);
} else if (value instanceof String) {
    cell.setCellValue((String) value);
}

Interview Tip

Understand the difference between getLastRowNum(), getPhysicalNumberOfRows() and getLastCellNum(). These are frequently useful when implementing Excel-based data-driven automation frameworks.

No comments:

Post a Comment