標籤:
public static List<List<String>> readExcelToList(String path, String sheetName, int rowNum, int colNum) {List<List<String>> resultList = new ArrayList<List<String>>();InputStream is = null;try {if (!new File(path).exists()) {return null;}is = new FileInputStream(path);Workbook wb = new HSSFWorkbook(is);Sheet sheet = wb.getSheet(sheetName);if (sheet != null) {if (rowNum <= 0) {rowNum = sheet.getLastRowNum() + 1;}for (int j = 0; j < rowNum; j++) {List<String> rowList = new ArrayList<String>();Row row = sheet.getRow(j);if (row == null) {row = sheet.createRow(j);}if (colNum <= 0) {colNum = row.getLastCellNum();}for (short k = 0; k < colNum; k = (short) (k + 1)) {Cell aCell = row.getCell(k);String cellVal = "";if (aCell == null) {aCell = row.createCell(k);}cellVal = convertCell(aCell);rowList.add(cellVal);}resultList.add(rowList);}}} catch (Exception e) {e.printStackTrace();} finally {try {if (is != null)is.close();} catch (IOException e) {e.printStackTrace();}}return resultList;} private static String convertCell(Cell cell) { NumberFormat formater = NumberFormat.getInstance(); formater.setGroupingUsed(false); String cellValue = ""; if (cell == null) { return cellValue; } switch (cell.getCellType()) { case 0: cellValue = formater.format(cell.getNumericCellValue()); break; case 1: cellValue = cell.getStringCellValue(); break; case 3: cellValue = cell.getStringCellValue(); break; case 4: cellValue = Boolean.valueOf(cell.getBooleanCellValue()).toString(); break; case 5: cellValue = String.valueOf(cell.getErrorCellValue()); break; case 2: default: cellValue = ""; } return cellValue.trim(); }
read excel to list