Read write excel file in Java and Apache POI

In order to read write excel file in Java and APACHE POI, we can use this method which uses FileInputStream, and XSSFWorkbook to get into the workbook and fetch the data written in the cells of the sheets. The arguments to the method are file path, sheet name, row index, and column index.

Function to read and write data
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

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

public class ExcelUtils {

  private static Workbook workbook;
  private static Sheet sheet;
  private static Cell cell;
  private static FileInputStream inputStream;
  private static FileOutputStream outputStream;

  //Method to read data from an Excel file
  public static String readData(String filePath, String sheetName, int rowNum, int colNum) throws IOException {
    inputStream = new FileInputStream(filePath);
    workbook = new XSSFWorkbook(inputStream);
    sheet = workbook.getSheet(sheetName);
    cell = sheet.getRow(rowNum).getCell(colNum);
    inputStream.close();
    return cell.toString();
  }

  //Method to write data to an Excel file
  public static void writeData(String filePath, String sheetName, int rowNum, int colNum, String data) throws IOException {
    inputStream = new FileInputStream(filePath);
    workbook = new XSSFWorkbook(inputStream);
    sheet = workbook.getSheet(sheetName);
    cell = sheet.getRow(rowNum).getCell(colNum);
    cell.setCellValue(data);
    outputStream = new FileOutputStream(filePath);
    workbook.write(outputStream);
    outputStream.close();
    inputStream.close();
  }
}
How to read data using the above readData function
String filePath = "data.xlsx";
String sheetName = "Sheet1";
int rowNum = 0;
int colNum = 0;
String data = ExcelUtils.readData(filePath, sheetName, rowNum, colNum);
How to write data using the above writeData function
String filePath = "data.xlsx";
String sheetName = "Sheet1";
int rowNum = 0;
int colNum = 0;
String data = "Test Data";
ExcelUtils.writeData(filePath, sheetName, rowNum, colNum, data);

You may also read

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.