帮我优化以下代码并解释为什么这么修改: public AjaxResult importDataMultipartFile file boolean updateSupport throws Exception Workbook workbook = null; InputStream inputStream = filegetInputStream;
修改后的代码如下:
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); }
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()); }
修改解释:
- 简化了获取文件扩展名的逻辑,使用了更直观的方式。
- 移除了对空指针的判断,使用了
Objects.requireNonNull确保file.getOriginalFilename()不为null。 - 删除了对workbook是否为null的判断,因为如果文件类型不支持,workbook会为null,后续的操作会抛出异常。
- 简化了获取sheet的逻辑,直接使用
workbook.getSheet(sheetName)获取指定名称的sheet。 - 在
workbookToInputStream方法中,直接返回创建的ByteArrayInputStream对象,省去了关闭ByteArrayOutputStream的步骤
原文地址: https://www.cveoy.top/t/topic/hQrA 著作权归作者所有。请勿转载和采集!