public static void readUserInfo() throws InvalidFormatException, IOException { String[] titles = { "收费编号", "收费性质", "姓名", "家庭住址", "工作单位", "电话", "手机", "小区楼号", "单元号", "楼层", "房间号", "建筑面积(㎡)", "面积依据", "A面积", "A超", "A轻体", "B面积", "B超", "B轻体", "用户编号", "所属楼前表表号" }; //用来存储标题和顺序的map,key为标题,value为顺序号 Map<String, Integer> titleMap = new HashMap<String, Integer>(); //将既定顺序写入map for (int i=0 ; i<titles.length; i++) { titleMap.put(titles[i], i); } Workbook wb = WorkbookFactory.create(new File("e:/test/userinfo.xls")); for (int numSheet = 0; numSheet < wb.getNumberOfSheets(); numSheet++) { Sheet xSheet = wb.getSheetAt(numSheet); if (xSheet == null) { continue; } // 获取第一行的标题内容 Row tRow = xSheet.getRow(0); //存储标题顺序的数组 Integer[] titleSort = new Integer[tRow.getLastCellNum()]; //循环标题 for (int titleNum = 0; titleNum < tRow.getLastCellNum(); titleNum++) { Cell tCell = tRow.getCell(titleNum); String title = ""; if (tCell == null || "".equals(tCell)) { } else if (tCell.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) {// 布尔类型处理 // logger.info(xCell.getBooleanCellValue()); } else if (tCell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {// 数值类型处理 title = doubleToString(tCell.getNumericCellValue()); } else {// 其他类型处理 title = tCell.getStringCellValue(); } //通过获取的标题,从map中读取顺讯号,写入保存标题顺序号的数组 Integer ts = titleMap.get(title); if (ts != null) { titleSort[titleNum] = ts; } } // 循环行Row for (int rowNum = 1; rowNum < xSheet.getLastRowNum() + 1; rowNum++) { Row xRow = xSheet.getRow(rowNum); if (xRow == null) { continue; } // 循环列Cell String[] v = new String[titleSort.length]; for (int cellNum = 0; cellNum < titleSort.length; cellNum++) { Cell xCell = xRow.getCell(cellNum); String value = ""; if (xCell == null || "".equals(xCell)) { } else if (xCell.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) {// 布尔类型处理 logger.info(xCell.getBooleanCellValue()); } else if (xCell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {// 数值类型处理 value = doubleToString(xCell.getNumericCellValue()); } else {// 其他类型处理 value = xCell.getStringCellValue(); } //按照标题顺序的编号来存储每一行记录 v[titleSort[cellNum]] = value; // logger.info("v[" + titleSort[cellNum] + "] = " + v[titleSort[cellNum]]); } //循环结果数组,获取的与既定顺序相同 for (int i = 0; i < v.length; i++) { logger.info(v[i]); } } } } |