poi读excel xlsx的工具类

tech2025-05-24  9

//得到workbook public Workbook readWorkBook(InputStream is) throws Exception { Workbook wb = null; try { /** 使用WorkbookFactory不用再去判断Excel因为版本不同而使用不同的方法 */ wb = WorkbookFactory.create(is); is.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (null != is) { try { is.close(); } catch (Exception e) { is = null; e.printStackTrace(); } } } return wb; }

后续的肯定要根据具体需求去写,但是基本步骤都是这样的

/**得到shell */ Sheet sheet = wb.getSheetAt(3); String sheetName = sheet.getSheetName(); /** 得到Excel的总行数 */ int rowCount = sheet.getPhysicalNumberOfRows(); /** 循环Excel的行 */ for (int i = 4; i < rowCount; i++) { ExcelExportModel model = new ExcelExportModel(); Row row = sheet.getRow(i); if (null == row) { continue; } //循环或者拿具体的单元格 //得到单元格总列数 int cellNum = row.getPhysicalNumberOfCells(); //通过下标取具体的单元格 Cell cell = row.getCell(0); //这里有一个要注意的就是获取的时候是按string去获取的 如果遇到int类型就会保存,为了避免我们一般将该单元格转为文本类型。 cell.setCellType(CellType.STRING);//将但余个内容转为文本. //获取值getStringCellValue String name= cell.getStringCellValue(); //变量名称前缀/对象名

两个比较常用到的String处理的工具 1.获取string中指定字符的个数

public static int count(String srcStr, String findStr) { int count = 0; Pattern pattern = Pattern.compile(findStr);// 通过静态方法compile(String regex)方法来创建,将给定的正则表达式编译并赋予给Pattern类 Matcher matcher = pattern.matcher(srcStr);// while (matcher.find()) {// boolean find() 对字符串进行匹配,匹配到的字符串可以在任何位置 count++; } return count; }

2.获取string中的出现第一个数字

public static int getFistNum(String s) { if (s == null || s.length() == 0) { return -1; } char c = s.charAt(0); if (c >= '0' && c <= '9') { return c - '0'; } else { return getFistNum(s.substring(1)); } }
最新回复(0)