How to Use Java to Read Excel

Written by joe wandy
  • Share
  • Tweet
  • Share
  • Pin
  • Email
How to Use Java to Read Excel
Excel spreadsheets can be processed conveniently in Java programs (Stockbyte/Stockbyte/Getty Images)

When writing a business-oriented application on the desktop, Java programmers often find themselves having data stored inside a Microsoft Excel file. If you find yourself in this situation, you can use the POI library created by the Apache Foundation. The POI library provides high-level mechanisms that allow Java programs to read and process Excel files conveniently. This allows you to save time and concentrate more on developing the important business logic of your Java application.

Skill level:


  1. 1

    Create a workbook reference in your Java code to the Excel spreadsheet that you want to process. Do this by using the "HSSFWorkbook" class. This will take a "FileInputStream" class that points to the actual Excel document that you want to read. For example, the following code will create a workbook to the Excel file that is defined in the string fileToBeRead.

    HSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(fileToBeRead));

  2. 2

    Refer to the actual worksheet inside the workbook by using either its index number or its name. For example, the following Java code will make a reference to the first worksheet in the workbook:

    HSSFSheet sheet = workbook.getSheetAt(0);

    Similarly, the following Java code will make a reference to the worksheet called 'Sheet1' in the workbook:

    HSSFSheet sheet = workbook.getSheet("Sheet1");

  3. 3

    You can now access the rows and cell values of the Excel worksheet by using the "get Row()", "get Cell()" and "getStringCellValues" methods. For example, the following code shows how you can get the value of the first cell in the first row of the worksheet:

    HSSFRow row = sheet.getRow(0);

    HSSFCell cell = row.getCell((short)0);


Tips and warnings

  • Frequently, when reading an Excel file, you want to loop through all rows in the worksheet and process the values accordingly. To do this, you can get an iterator over all the rows in the current sheet. For example:
  • Iterator rows = sheet.rowIterator ();
  • while (rows.hasNext ())
  • {
  • HSSFRow row = ();
  • ...
  • }
  • Not limited only to reading, you can also use the POI library to write and modify Excel files.

Don't Miss

  • All types
  • Articles
  • Slideshows
  • Videos
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the site, you consent to the use of cookies. For more information, please see our Cookie policy.