importjava.util.ArrayList;importjava.io.FileInputStream;importjava.io.IOException;importorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.ss.usermodel.Cell;importorg.apache.poi.ss.usermodel.Row;importorg.apache.poi.ss.usermodel.Sheet;importorg.apache.poi.ss.usermodel.Workbook;importorg.apache.poi.xssf.usermodel.XSSFWorkbook;public classReadExcel {public ArrayList>readExcel(String fileName,String path) {
ArrayList> Row =new ArrayList>();try{
Workbook workBook= null;try{
workBook= new XSSFWorkbook(path+"\\"+fileName);
}catch(Exception ex) {
workBook= new HSSFWorkbook(new FileInputStream(path+"\\"+fileName));
}for (int numSheet = 0; numSheet < workBook.getNumberOfSheets(); numSheet++) {
Sheet sheet=workBook.getSheetAt(numSheet);if (sheet == null) {continue;
}//循环行Row
for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
Row row=sheet.getRow(rowNum);if (row == null) {continue;
}//循环列Cell
ArrayList arrCell =new ArrayList();for (int cellNum = 0; cellNum <= row.getLastCellNum(); cellNum++) {
Cell cell=row.getCell(cellNum);if (cell == null) {continue;
}
arrCell.add(getValue(cell));
}
Row.add(arrCell);
}
}
}catch(IOException e) {
System.out.println("e:"+e);
}returnRow;
}privateString getValue(Cell cell) {if (cell.getCellType() ==cell.CELL_TYPE_BOOLEAN) {returnString.valueOf(cell.getBooleanCellValue());
}else if (cell.getCellType() ==cell.CELL_TYPE_NUMERIC) {returnString.valueOf(cell.getNumericCellValue());
}else{returnString.valueOf(cell.getStringCellValue());
}
}public static voidmain(String[] args) {
ReadExcel s= newReadExcel();//ArrayList> row=s.readExcel("TEST.xlsx","D:\\Program Files\\Java");
ArrayList> row=s.readExcel("TEST1.xls","D:\\Program Files\\Java");
System.out.println("size:"+row.size());for (ArrayListcell : row) {for(String str : cell) {
System.out.println(str);
}
}
}
}