1.先引入hutool的相关依赖
cn.hutool hutool-all 5.8.4 org.apache.poi poi-ooxml 4.1.2
2.导出
创建一个Controller进行测试
@GetMapping(path = "/export") public void export(HttpServletResponse response,OrderPageRequest orderPageRequest)throws IOException { { // 查询导出订单数据 List ordereList = getOrdereList(orderPageRequest); if (CollectionUtils.isEmpty(ordereList)) { throw new BusinessException("暂无数据!"); } //在内存操作,写到浏览器 ExcelWriter writer = ExcelUtil.getWriter(true); //自定义别名 writer.addHeaderAlias("orderCode", "订单编码"); writer.addHeaderAlias("addressName", "送达方名称"); writer.addHeaderAlias("amount", "订单金额"); writer.addHeaderAlias("orderStatusDesc", "订单状态"); writer.addHeaderAlias("createTime", "创建时间"); writer.addHeaderAlias("submitTime", "提交时间"); writer.addHeaderAlias("createTime", "创建时间"); //只保留别名的数据 writer.setOnlyAlias(true); // 默认配置 writer.write(ordereList, true); // 设置content—type response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset:utf-8"); // 设置 String fileName = URLEncoder.encode("订单导出", "UTF-8"); //Content-disposition是MIME协议的扩展,MIME协议指示MIME用户代理如何显示附加的文件。 response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx"); ServletOutputStream outputStream = response.getOutputStream(); //将Writer刷新到OutPut writer.flush(outputStream, true); outputStream.close(); writer.close(); }
3.导出效果
4.Excel 表格导入 实现
@PostMapping(path="/import") public List importData(@RequestParam("file") MultipartFile file) throws IOException { //字节输入流 InputStream inputStream = file.getInputStream(); //通过输入流创建ExcelReader 对象 ExcelReader reader = ExcelUtil.getReader(inputStream); // 获取模板第一行第一列判断模板是否正确 if (!"*客户物料号".equals(reader.getOrCreateRow(0).getCell(0).toString())) { throw new BusinessException("请按正确的模板导入!"); } // 导入模板的列名要跟这个一致 不然字段是映射不上 reader.addHeaderAlias("*客户物料号","customerSkuCode"); reader.addHeaderAlias("*物料号","skuCode"); reader.addHeaderAlias("*数量","quantity"); reader.addHeaderAlias("*单位","unitDesc"); List list = reader.readAll(OrderItemResponse.class); for (int i = 0; i < list.size(); i++) { OrderItemResponse item = list.get(i); // 设置模板行号 用于错误提示 item .setImportNo(i+2); String msg = ""; // 校验必填 if (CollectionUtils.isNull(item.getSkuCode()){ msg = "客户物料号不能为空;"; } if (CollectionUtils.isNull(item.getUnitDesc())) { msg = msg + "数量单位不能为空;"; } item.setErrorMsg(msg); } // 保存 service.BatchAdd(list); // 把集合返回 用于前端展示成功行/失败行 return list; }
来源地址:https://blog.csdn.net/lv_hang515888/article/details/131422906