Java解析excel文件
· 获取excel文件(根据后端框架不同,获取方式不相同)
// 获取excel文件 ecEcardRequest.setRequestType("07"); // 电子卡单状态批量查询表示 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile certificationPrintNoFile = multipartRequest.getFile("certificationPrintNoFile"); InputStream inputStream = certificationPrintNoFile.getInputStream(); Workbook workbook = Workbook.getWorkbook(inputStream); // 调用封装好的方法解析 List<String> certificationPrintNoList = analysisExcel(multipartRequest, workbook);
· 解析文件
/** * 解析excel信息 * @param request * @param workbook * @param list */ private List<String> analysisExcel(HttpServletRequest request, Workbook workbook) { List<String> certificationPrintNoList = new ArrayList<>(); Sheet sheet = workbook.getSheet(0); if (sheet.getRows() <= 1) { return certificationPrintNoList; } for (int row = 1; row < sheet.getRows(); row++) { String certificationPrintNo = getCellValue(sheet,0,row).replaceAll(" ",""); if (StringUtils.isNotEmpty(certificationPrintNo)) { certificationPrintNoList.add(certificationPrintNo); } } return certificationPrintNoList; } /** * 获取单元格中的值 * @param sheet * @param column * @param row * @return */ private String getCellValue(Sheet sheet, int column, int row) { if (sheet == null || column < 0 || row < 0) { return ""; } Cell cell = sheet.getCell(column, row); if (cell == null) { return ""; } String contents = cell.getContents(); if (StringUtils.isEmpty(contents)) { return ""; } else { return contents.trim(); } }