On a recent project we had the need to process Microsoft Excel spreadsheets. We chose to use an API, called JExcel, to read, write, and process Excel files. This post will focus on reading and processing an Excel spreadsheet.

To start you'll need to create a Workbook, which can be done by reading from a File or InputStream. Next, get each Sheet to process by calling .getSheets(). Need to be sure to close the workbook to free up resources by calling .close() once processing is complete.

Workbook workbook = Workbook.getWorkbook(
 new FileInputStream("../upload_dir/upload_file.xls")
);
 
if (workbook != null && workbook.getNumberOfSheets() > 0) {
 for (Sheet sheet : workbook.getSheets()) {
 parseSheet(sheet);
 }
}

Once you have a Sheet you can get each Row, which will be an Array of Cells and then get the contents of each Cell as a String. The API also gives you the ability to get a cell's value of a particular type (i.e. Number, Date, etc.). See the API documentation for examples.

private void parseSheet(Sheet sheet) {
 if (sheet != null && sheet.getColumns() > 0 && sheet.getRows > 0) {
 for (int i = 1; i  sheet.getRows(); i++) {
 Cell[] row = sheet.getRow(i);
 String cell1 = row[0].getContents();
 String cell3 = row[1].getContents();
 String cell2 = row[2].getContents();
 }
 }
}

*** Note - One downfall of the current version (2.6.10) is that it cannot read Microsoft 2007 Excel file version (.xlsx). Hopefully the next release will address this issue.