public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception { Workbook workbook = null; InputStream inputStream = file.getInputStream(); String fileExtension = getFileExtension(Objects.requireNonNull(file.getOriginalFilename())); // 根据文件类型进行区分 if (fileExtension.equals("xlsx")) { workbook = new XSSFWorkbook(inputStream); } else if (fileExtension.equals("xls")) { workbook = new HSSFWorkbook(inputStream); } else { return AjaxResult.error("Invalid file extension"); }

String sheetName = "a-HKG BW WHSE-in bound"; // 导入信息的工作表名称
Sheet sheet = workbook.getSheet(sheetName);
if (sheet == null) {
    throw new IllegalArgumentException("Sheet with name " + sheetName + " does not exist");
}
InputStream getSheetInputStream = workbookToInputStream(workbook);
ExcelUtil<AHkgBwWhseInBound> util = new ExcelUtil<>(AHkgBwWhseInBound.class);
List<AHkgBwWhseInBound> dataManagementList = util.importExcel(getSheetInputStream, 1);
String operName = ShiroUtils.getSysUser().getLoginName();
String message = aHkgBwWhseInBoundService.importData(dataManagementList, updateSupport, operName);
return AjaxResult.success(message);

}

private static String getFileExtension(String fileName) { int dotIndex = fileName.lastIndexOf("."); if (dotIndex != -1 && dotIndex != 0) { return fileName.substring(dotIndex + 1); } else { return ""; } }

private static InputStream workbookToInputStream(Workbook workbook) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); workbook.write(byteArrayOutputStream); return new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); }

Explanation of Modifications:

  1. Added a check for invalid file extension. If the file extension is neither "xlsx" nor "xls", an error message is returned.
  2. Improved error handling by throwing IllegalArgumentException if the specified sheet does not exist.
  3. Provided a more descriptive variable name for the InputStream obtained from workbookToInputStream method.
  4. Added comments to explain the purpose of certain code blocks
优化以下代码并解释修改部分:public AjaxResult importDataMultipartFile file boolean updateSupport throws Exception Workbook workbook = null; InputStream inputStream = filegetInputStream; String fileExtensi

原文地址: https://www.cveoy.top/t/topic/hQrT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录