You are currently viewing Excel File Reading Made Simple: A Java Developer’s Guide

Excel File Reading Made Simple: A Java Developer’s Guide

In the realm of data processing and analysis, Excel files are a common and widely used format. Being able to efficiently read data from Excel files is a valuable skill for Java developers.

Setting up the Dependencies

To get started, you need to include the necessary dependencies in your Java project. In this case, we’ll be using Apache POI, which can be downloaded from the official Apache POI website. Make sure to download the appropriate version of Apache POI based on your Java version and project requirements. Once you have downloaded the library, make sure to add it to your project’s classpath.

Creating the ExcelReader Class

The ExcelReader class is a utility class that utilizes the Apache POI library to facilitate reading data from Excel files in Java:

import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;

/**
 * Utility class for reading data from an Excel file using Apache POI library.
 */
public class ExcelReader {

    private final String filename;

    public ExcelReader(String filename) {
        this.filename = filename;
    }

    /**
     * Reads the first sheet from the Excel file.
     *
     * @return The first sheet in the Excel file.
     * @throws IOException If an I/O error occurs while reading the file.
     */
    public Sheet read() throws IOException {

        try (Workbook workbook = this.createWorkbook()) {
            return workbook.getSheetAt(0);
        }

    }

    /**
     * Reads a specific sheet from the Excel file by name.
     *
     * @param sheetName The name of the sheet to read.
     * @return The sheet with the specified name.
     * @throws IOException            If an I/O error occurs while reading the file.
     * @throws SheetNotFoundException If the sheet with the specified name does not exist.
     */
    public Sheet read(String sheetName) throws IOException, SheetNotFoundException {

        try (Workbook workbook = this.createWorkbook()) {

            // Get the sheet by name
            Sheet sheet = workbook.getSheet(sheetName);

            if (sheet == null)
                throw new SheetNotFoundException(sheetName);

            return sheet;

        }

    }

    /**
     * Creates a workbook from the Excel file.
     *
     * @return The created workbook.
     * @throws IOException If an I/O error occurs while reading the file.
     */
    private Workbook createWorkbook() throws IOException {
        try (FileInputStream fileInputStream = new FileInputStream(this.filename)) {
            return new XSSFWorkbook(fileInputStream);
        }
    }

    /**
     * Custom exception class to indicate that a specific sheet was not found in the Excel file.
     */
    public static class SheetNotFoundException extends  Exception {
        public SheetNotFoundException(String sheetName) {
            super(String.format("Sheet '%s' could not be found.", sheetName));
        }

    }

}

Reading Excel Files

The provided code demonstrates the usage of the ExcelReader class for reading data from an Excel file:

import org.apache.poi.ss.usermodel.*;
import java.io.IOException;

public class Main {

    public static void main(String[] args) {

        ExcelReader reader = new ExcelReader("excel.xlsx");

        try {

            // Get data from the first sheet (index 0)
            Sheet sheet = reader.read();

            /*
                Get data from a specified sheet by name
                Sheet sheet = reader.read("Sheet1");
            */

            // Iterate through each row in the sheet
            sheet.forEach(row -> {

                // Iterate through each cell in the row
                row.forEach(cell -> {

                    // Print the cell value
                    System.out.print(cell.getStringCellValue() + "\t");

                });

                System.out.println();

            });

        } catch (IOException exception) {

            // Handle any IO exception that may occur
            System.out.println(exception.getMessage());

        }

    }

}

There you have it! In case you were wondering how to create Excel files, we already have an article titled Creating Excel Files in Java available on our website. I hope you found it informative. If you wish to see more content like this, please consider subscribing. 😊

Leave a Reply