How do I read from an Excel file using POI?
Author: Deron Eriksson
Description: This Java tutorial describes how to read from an Excel file using Apache POI.
Tutorial created using:
Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.1
In another tutorial, we saw how we could use the ApacheSW Jakarta POI project to write data to an Excel (xls) file. This library can also be used to read data from an Excel file. The Apache Jakarta POI project can be found at http://jakarta.apache.org/poi/. Within the POI project, POI-HSSF focuses on Excel documents. The HSSF Quick Guide at http://jakarta.apache.org/poi/hssf/quick-guide.html is a great resouce for quickly getting up to speed with POI-HSSF. In this tutorial I'll use the project structure that we created for the other tutorial. This project contains the POI jarW file in its classpathW. We will create a class that reads in data from an Excel file and displays it. The Excel file that we will use is the 'poi-test.xls' file that we previously created. The poi-test.xls file is located at the root level of our project and is shown here: poi-test.xlsThe PoiReadExcelFile class will read in the 'poi-test.xls' file into an HSSFWorkbook object. The 'POI Worksheet' will then be read into an HSSFWorksheet object, and then the values within the A1, B1, C1, and D1 cells will be read and displayed to standard output. PoiReadExcelFile.javapackage test; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Date; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; public class PoiReadExcelFile { public static void main(String[] args) { try { FileInputStream fileInputStream = new FileInputStream("poi-test.xls"); HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream); HSSFSheet worksheet = workbook.getSheet("POI Worksheet"); HSSFRow row1 = worksheet.getRow(0); HSSFCell cellA1 = row1.getCell((short) 0); String a1Val = cellA1.getStringCellValue(); HSSFCell cellB1 = row1.getCell((short) 1); String b1Val = cellB1.getStringCellValue(); HSSFCell cellC1 = row1.getCell((short) 2); boolean c1Val = cellC1.getBooleanCellValue(); HSSFCell cellD1 = row1.getCell((short) 3); Date d1Val = cellD1.getDateCellValue(); System.out.println("A1: " + a1Val); System.out.println("B1: " + b1Val); System.out.println("C1: " + c1Val); System.out.println("D1: " + d1Val); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } (Continued on page 2) Related Tutorials: |