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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| @Test public void testCellType() throws Exception {
FileInputStream inputStream = new FileInputStream(PATH + "工资申报表.xls");
Workbook workbook = new HSSFWorkbook(inputStream); Sheet sheet = workbook.getSheetAt(0); Row rowTitle = sheet.getRow(0); if (rowTitle != null) {
int cellCount = rowTitle.getLastCellNum(); for (int cellNum = 0; cellNum < cellCount; cellNum++) {
Cell cell = rowTitle.getCell(cellNum); if (cell != null) {
int cellType = cell.getCellType(); String cellValue = cell.getStringCellValue(); System.out.print(cellValue + " | "); } } System.out.println(); } int rowCount = sheet.getPhysicalNumberOfRows(); for (int rowNum = 1; rowNum < rowCount; rowNum++) {
Row rowData = sheet.getRow(rowNum); if (rowData != null) {
int cellCount = rowData.getLastCellNum(); for (int cellNum = 0; cellNum < cellCount; cellNum++) {
System.out.print("[" + (rowNum + 1) + "-" + (cellNum + 1) + "]"); Cell cell = rowData.getCell(cellNum); if (cell != null) {
int cellType = cell.getCellType(); String cellValue = ""; switch (cellType) {
case HSSFCell.CELL_TYPE_STRING: System.out.print("【STRING】"); cellValue = cell.getStringCellValue(); break; case HSSFCell.CELL_TYPE_BOOLEAN: System.out.print("【BOOLEAN】"); cellValue = String.valueOf(cell.getBooleanCellValue()); break; case HSSFCell.CELL_TYPE_BLANK: System.out.print("【BLANK】"); break; case HSSFCell.CELL_TYPE_NUMERIC: System.out.print("【NUMERIC】"); if (HSSFDateUtil.isCellDateFormatted(cell)) { System.out.print("【日期】"); Date date = cell.getDateCellValue(); cellValue = new DateTime(date).toString("yyyy-MM-dd"); } else {
System.out.print("【数字 转换为字符串输出】"); cell.setCellType(HSSFCell.CELL_TYPE_STRING); cellValue = cell.toString(); } break; case HSSFCell.CELL_TYPE_ERROR: System.out.print("【数据类型错误】"); break; } System.out.println(cellValue); } } } }
inputStream.close(); }
|