• EasyExcel导入导出


    一,工具类

    1. import cn.hutool.json.JSONUtil;
    2. import com.alibaba.excel.EasyExcel;
    3. import com.alibaba.excel.read.listener.PageReadListener;
    4. import com.alibaba.excel.util.MapUtils;
    5. import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
    6. import org.springframework.web.multipart.MultipartFile;
    7. import javax.servlet.http.HttpServletResponse;
    8. import java.io.IOException;
    9. import java.net.URLEncoder;
    10. import java.util.List;
    11. import java.util.Map;
    12. public class ExcelUtils <T> {
    13. /**
    14. * 文件下载并且失败的时候返回json(默认失败了会返回一个有部分数据的Excel)
    15. *
    16. * @since 2.1.1
    17. */
    18. public static <T> void excelDownload(HttpServletResponse response, String fileName, Class clazz, List<T> data) throws IOException {
    19. // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
    20. try {
    21. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    22. response.setCharacterEncoding("utf-8");
    23. // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
    24. response.setHeader("Content-disposition","attachment;filename*=utf-8''"+ URLEncoder.encode(fileName,"UTF-8").replaceAll("\\+","%20")+".xlsx");
    25. // LongestMatchColumnWidthStyleStrategy 自动调节单元格宽度策略
    26. EasyExcel.write(response.getOutputStream(),clazz).autoCloseStream(Boolean.FALSE).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).sheet(fileName).doWrite(data);
    27. } catch (Exception e) {
    28. // 重置response
    29. response.reset();
    30. response.setContentType("application/json");
    31. response.setCharacterEncoding("utf-8");
    32. Map<String, String> map = MapUtils.newHashMap();
    33. map.put("status", "failure");
    34. map.put("message", "下载文件失败" + e.getMessage());
    35. response.getWriter().println(JSONUtil.toJsonStr(map));
    36. }
    37. }
    38. public static <T> void excelRead(MultipartFile excel, Class clazz , List<T> list) throws IOException {
    39. // 这里默认每次会读取100条数据 然后返回过来 直接调用使用数据就行
    40. // 具体需要返回多少行可以在`PageReadListener`的构造函数设置
    41. EasyExcel.read(excel.getInputStream(), clazz, new PageReadListener<T>(dataList -> {
    42. list.addAll(dataList);
    43. })).sheet().doRead();
    44. }
    45. }

    二,接口

            1,下载模板接口

                  a,  模板类

    1. @Data
    2. @EqualsAndHashCode
    3. public class ParkingBerthTemplateVO{
    4. @ExcelProperty(value = "停车场名称*",index = 0)
    5. private String parkingName;
    6. @ExcelProperty(value = "泊位编码*",index = 1)
    7. private String berthCode;
    8. @ExcelProperty(value = "设备编码*",index = 2)
    9. private String deviceCode;
    10. }

                 b,   接口

    1. @ApiOperation(value = "下载导入模板", notes = "下载导入模板")
    2. @GetMapping("template")
    3. public void downloadTemplate(HttpServletResponse response) throws IOException {
    4. String fileName = "导入模板";
    5. ExcelUtils.excelDownload(response, fileName, ParkingBerthTemplateVO.class, null);
    6. }

            2,导入接口                

    1. @ApiOperation(value = "导入", notes = "导入")
    2. @PostMapping("import")
    3. public Result<Boolean> berthImport(MultipartFile excel ) throws IOException {
    4. List<ParkingBerthTemplateVO> voList = new ArrayList<>();
    5. ExcelUtils.excelRead(excel,ParkingBerthTemplateVO.class, voList);
    6. Assert.isFalse(CollectionUtil.isEmpty(voList), "文件不能为空");
    7. // 保存逻辑
    8. // parkingBerthService.berthImport(voList);
    9. return Result.ok();
    10. }

            3,导出接口

                    a,导出vo类

    1. /**
    2. * 停车订单
    3. */
    4. @Data
    5. @SuperBuilder
    6. @NoArgsConstructor
    7. @Accessors(chain = true)
    8. @ExcelIgnoreUnannotated
    9. public class OrderParkingExportDTO {
    10. @ColumnWidth(10)
    11. @ExcelProperty(value = "ID" ,index = 0)
    12. private Long id;
    13. @ExcelProperty(value = "供应商ID",index = 1)
    14. private Long tenantId;
    15. // @ColumnWidth(100)
    16. @ExcelProperty(value = "订单号",index = 2)
    17. private String orderCode;
    18. @ExcelProperty(value = "停车场ID",index = 3)
    19. private Long parkingId;
    20. @ExcelProperty(value = "停车场名称",index = 4 )
    21. private String parkingName;
    22. @ExcelProperty(value = "客户ID",index = 5 )
    23. private Long customerId;
    24. @ExcelProperty(value = "无牌/有牌",index = 6 )
    25. private String hasPlateNoString;
    26. @ExcelProperty(value = "车牌",index = 7 )
    27. private String plateNo;
    28. private PlateColor plateColor;
    29. @ExcelProperty(value = "车牌颜色",index = 8 )
    30. private String plateColorString;
    31. public void dataProcessor(){
    32. if(hasPlateNo!= null){
    33. hasPlateNoString = hasPlateNo == true ? "有牌" : "无牌";
    34. }
    35. if(plateColor!= null){
    36. plateColorString = plateColor.getDesc();
    37. }
    38. }
    39. }

                   b, 接口

    1. @ApiOperation(value = "列表导出", notes = "列表导出")
    2. @PostMapping("download")
    3. public void download(HttpServletResponse response,@RequestBody OrderParkingQueryVO vo, @ApiIgnore LoginSysUser loginSysUser) throws IOException {
    4. OrderParkingQueryDTO dto = OrderParkingConverter.INSTANCE.orderParking(vo, loginSysUser);
    5. List<OrderParking> list = orderParkingService.list(dto);
    6. List<OrderParkingExportDTO> data = OrderParkingConverter.INSTANCE.entityToExportDto(list);
    7. data.forEach(item -> item.dataProcessor());
    8. String fileName = "列表导出";
    9. ExcelUtils.excelDownload(response,fileName,OrderParkingExportDTO.class,data);
    10. }

  • 相关阅读:
    1-氨丙基-3-甲基咪唑溴盐离子液体修饰碳量子点(L-CQDs)负载TiO2纳米颗粒(试剂)
    【Android开发】学习笔记(二)
    网站部署SSL证书是否会影响网站流量?
    postgresql并行查询(高级特性)
    【Linux】环境基础开发工具使用 - 软件包管理yum _vim _gcc/g++ _gdb
    Verilog实现SPI通信协议驱动设计
    货币银行学名词解释
    华为od德科面试数据算法真题 2022-6-10 整形数组的最大连续子串的长度
    某城商行两地三中心建设存储架构规划及方案验证实践
    MimicMotion - 一张图片实现视频跳舞,腾讯开源照片跳舞模型 本地一键整合包下载
  • 原文地址:https://blog.csdn.net/daizikui/article/details/136561960