1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| public void testCellType() throws IOException { InputStream inputStream = new FileInputStream("/Users/panyurou/IdeaProjects/exceldemo/src/test/resources/明细表.xlsx"); final XSSFWorkbook workbook = new XSSFWorkbook(inputStream); final XSSFSheet sheet = workbook.getSheetAt(0); final XSSFRow headerRow = sheet.getRow(0); final int colCount = headerRow.getPhysicalNumberOfCells(); for (int i = 0; i < colCount; i++) { final XSSFCell cell = headerRow.getCell(i); if(cell != null){ final String cellValue = cell.getStringCellValue(); System.out.print(cellValue + "|"); } } System.out.println(); final int rowsCount = sheet.getPhysicalNumberOfRows(); for (int i = 1; i < rowsCount; i++) { final XSSFRow row = sheet.getRow(i); for (int j = 0; j < colCount; j++) { final XSSFCell cell = row.getCell(j); if(cell != null){ final CellType cellType = cell.getCellType(); String cellValue = getCellValue(cell, cellType); System.out.print(cellValue + "|"); } } System.out.println(); } inputStream.close(); }
private String getCellValue(XSSFCell cell, CellType cellType) { String cellValue = ""; switch (cellType){ case STRING: cellValue = cell.getStringCellValue(); break; case NUMERIC: if(DateUtil.isCellDateFormatted(cell)){ final Date date = cell.getDateCellValue(); cellValue = new DateTime(date).toString("yyyy-MM-dd"); }else{ cellValue = String.valueOf(cell.getNumericCellValue()); } break; case FORMULA: cellValue = cell.getCellFormula(); break; case BOOLEAN: cellValue = String.valueOf(cell.getBooleanCellValue()); break; case ERROR: System.out.println("类型错误"); break; } return cellValue; }
|