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:
Other People Are Reading
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));
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");
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 = rows.next ();
- Not limited only to reading, you can also use the POI library to write and modify Excel files.
- 20 of the funniest online reviews ever
- 14 Biggest lies people tell in online dating sites
- Hilarious things Google thinks you're trying to search for