Java tutorial
package com.appspot.backstreetfoodies.server; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.ArrayList; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; /** * Parses one sheet of a XLS source into a two dimensional table represented as * an array list of an array list of strings. If a row contains an empty cell, * or does not contain exactly the same number of cells as expected, then that * entire row will also be discarded. * * This class uses Apache POI for parsing XLS data. Use under Apache License: * http://www.apache.org/licenses/LICENSE-2.0 */ public class XLSParser { public static final int HEADER_ROW = 0; private int numColumns = 0; private ArrayList<ArrayList<String>> xlsData = new ArrayList<ArrayList<String>>(); public XLSParser(InputStream inputStream, int sheetIndex, int numColumnsExpected) throws IOException { HSSFWorkbook workbook = new HSSFWorkbook(inputStream); HSSFSheet sheet = workbook.getSheetAt(sheetIndex); Iterator<Row> rowIterator = sheet.iterator(); Iterator<Cell> cellIterator; numColumns = numColumnsExpected; while (rowIterator.hasNext()) { int numCellsInRow = 0; Row row = rowIterator.next(); cellIterator = row.cellIterator(); ArrayList<String> temp = new ArrayList<String>(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: if (!String.valueOf(cell.getNumericCellValue()).isEmpty()) { numCellsInRow++; temp.add(String.valueOf(cell.getNumericCellValue())); } break; case Cell.CELL_TYPE_STRING: if (!cell.getStringCellValue().isEmpty()) { numCellsInRow++; temp.add(cell.getStringCellValue().trim()); } break; default: break; } } if (numCellsInRow == numColumnsExpected) { xlsData.add(temp); } } } /** * Get the number of rows, including the header row, in the parsed * data * * @return the number of rows in the parsed data */ public int getNumRows() { return xlsData.size(); } /** * Get the number of columns in the parsed data * * @return the number of columns in the parsed data */ public int getNumColumns() { return numColumns; } /** * Get the specified row which contains the cell values of that row. * * @param rowNumber * the specific row number to obtain data from * @return all of the cell data within the row. */ public ArrayList<String> getRow(int rowNumber) { return xlsData.get(rowNumber); } }