public classExcelReader {privateString filePath;privateString sheetName;privateWorkbook workBook;privateSheet sheet;private ListcolumnHeaderList;private List>listData;private List>mapData;private booleanflag;publicExcelReader(String filePath, String sheetName) {this.filePath =filePath;this.sheetName =sheetName;this.flag = false;this.load();
}private voidload() {
FileInputStream inStream= null;try{
inStream= new FileInputStream(newFile(filePath));
workBook=WorkbookFactory.create(inStream);
sheet=workBook.getSheet(sheetName);
}catch(Exception e) {
e.printStackTrace();
}finally{try{if(inStream!=null){
inStream.close();
}
}catch(IOException e) {
e.printStackTrace();
}
}
}privateString getCellValue(Cell cell) {
String cellValue= "";
DataFormatter formatter= newDataFormatter();if (cell != null) {switch(cell.getCellType()) {caseCell.CELL_TYPE_NUMERIC:if(DateUtil.isCellDateFormatted(cell)) {
cellValue=formatter.formatCellValue(cell);
}else{double value =cell.getNumericCellValue();int intValue = (int) value;
cellValue= value - intValue == 0 ?String.valueOf(intValue) : String.valueOf(value);
}break;caseCell.CELL_TYPE_STRING:
cellValue=cell.getStringCellValue();break;caseCell.CELL_TYPE_BOOLEAN:
cellValue=String.valueOf(cell.getBooleanCellValue());break;caseCell.CELL_TYPE_FORMULA:
cellValue=String.valueOf(cell.getCellFormula());break;caseCell.CELL_TYPE_BLANK:
cellValue= "";break;caseCell.CELL_TYPE_ERROR:
cellValue= "";break;default:
cellValue=cell.toString().trim();break;
}
}returncellValue.trim();
}private voidgetSheetData() {
listData= new ArrayList>();
mapData= new ArrayList>();
columnHeaderList= new ArrayList();int numOfRows = sheet.getLastRowNum() + 1;for (int i = 0; i < numOfRows; i++) {
Row row=sheet.getRow(i);
Map map = new HashMap();
List list = new ArrayList();if (row != null) {for (int j = 0; j < row.getLastCellNum(); j++) {
Cell cell=row.getCell(j);if (i == 0){
columnHeaderList.add(getCellValue(cell));
}else{
map.put(columnHeaderList.get(j),this.getCellValue(cell));
}
list.add(this.getCellValue(cell));
}
}if (i > 0){
mapData.add(map);
}
listData.add(list);
}
flag= true;
}public String getCellData(int row, intcol){if(row<=0 || col<=0){return null;
}if(!flag){this.getSheetData();
}if(listData.size()>=row && listData.get(row-1).size()>=col){return listData.get(row-1).get(col-1);
}else{return null;
}
}public String getCellData(introw, String headerName){if(row<=0){return null;
}if(!flag){this.getSheetData();
}if(mapData.size()>=row && mapData.get(row-1).containsKey(headerName)){return mapData.get(row-1).get(headerName);
}else{return null;
}
}public static voidmain(String[] args) {
ExcelReader eh= new ExcelReader("E:\\workspace\\test.xls","Sheet1");
System.out.println(eh.getCellData(1, 1));
System.out.println(eh.getCellData(1, "test1"));
}
}