SpringBoot导入导出
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.3.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency>
导出Excel模版
@GetMapping("/getMaterialTypeImportTemplate")public void getMaterialTypeImportStencil(HttpServletResponse response) {materialTypeService.getMaterialTypeImportTemplate(response);}
@Overridepublic void getMaterialTypeImportTemplate(HttpServletResponse response) {String name = "物料类型清单-模板.xlsx";InputStream inputStream = ResourceUtil.getStream("classpath:template/" + name);try {response.setContentType("application/octet-stream");String gbkName = new String(name.getBytes(CharsetUtil.GBK), StandardCharsets.ISO_8859_1);response.setHeader("Content-disposition", "attachment;filename=" + gbkName);response.flushBuffer();write(response, inputStream);} catch (IOException e) {throw new RuntimeException(e);}}/*** 将输入流写入response的输出流** @param response {@link HttpServletResponse}* @param inputStream 文件输入流*/private void write(HttpServletResponse response, InputStream inputStream) {// 写入responseOutputStream out = null;try {out = response.getOutputStream();int len;byte[] b = new byte[1024];while ((len = inputStream.read(b)) != -1) {out.write(b, 0, len);}out.flush();} catch (IOException e) {e.printStackTrace();} finally {try {if (out != null) {out.close();}} catch (Exception e) {e.printStackTrace();}}}
导入Excel
@PostMapping("/importMaterialType")public ResultModel<?> importMaterialType(@RequestParam("orgId") Long orgId,@RequestPart("excel") MultipartFile multipartFile) {return ResultUtil.success("成功", materialTypeService.importMaterialType(multipartFile, orgId));}
@Overridepublic boolean importMaterialType(MultipartFile multipartFile, Long orgId) {Long userId = ThreadLocalHolder.getSessionId();String originalFilename = multipartFile.getOriginalFilename();String suffix = Objects.requireNonNull(originalFilename).substring(originalFilename.lastIndexOf(".") + 1).toLowerCase(Locale.ENGLISH);if (!"xlsx".equals(suffix) && !"xls".equals(suffix)) {throw new CustomException("文件类型不合法, 需为'xlsx'或'xls'");}InputStream inputStream;try {inputStream = multipartFile.getInputStream();} catch (IOException e) {throw new RuntimeException(e);}ExcelReader reader = ExcelUtil.getReader(inputStream);reader.addHeaderAlias("一级分类", "firstTypeName");reader.addHeaderAlias("二级分类", "secondTypeName");reader.addHeaderAlias("计量单位", "materialTypeUnit");reader.addHeaderAlias("数量", "amount");List<BimMaterialTypeImportVo> list = reader.readAll(BimMaterialTypeImportVo.class);// ……}

