EasyExcel导入导出

一,工具类

import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

public class ExcelUtils <T> {


    /**
     * 文件下载并且失败的时候返回json(默认失败了会返回一个有部分数据的Excel)
     *
     * @since 2.1.1
     */
    public static <T> void excelDownload(HttpServletResponse response, String fileName, Class clazz, List<T> data) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            response.setHeader("Content-disposition","attachment;filename*=utf-8''"+ URLEncoder.encode(fileName,"UTF-8").replaceAll("\\+","%20")+".xlsx");
            // LongestMatchColumnWidthStyleStrategy 自动调节单元格宽度策略
            EasyExcel.write(response.getOutputStream(),clazz).autoCloseStream(Boolean.FALSE).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).sheet(fileName).doWrite(data);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSONUtil.toJsonStr(map));
        }
    }


    public static <T> void excelRead(MultipartFile excel, Class clazz , List<T> list) throws IOException {
        // 这里默认每次会读取100条数据 然后返回过来 直接调用使用数据就行
        // 具体需要返回多少行可以在`PageReadListener`的构造函数设置
        EasyExcel.read(excel.getInputStream(), clazz, new PageReadListener<T>(dataList -> {
            list.addAll(dataList);
        })).sheet().doRead();
    }
}

二,接口

1,下载模板接口

a, 模板类

@Data
@EqualsAndHashCode
public class ParkingBerthTemplateVO{

    @ExcelProperty(value = "停车场名称*",index = 0)
    private String parkingName;

    @ExcelProperty(value = "泊位编码*",index = 1)
    private String berthCode;

    @ExcelProperty(value = "设备编码*",index = 2)
    private String deviceCode;

}

b, 接口

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

2,导入接口

        @ApiOperation(value = "导入", notes = "导入")
        @PostMapping("import")
        public Result<Boolean> berthImport(MultipartFile excel ) throws IOException {

                List<ParkingBerthTemplateVO> voList = new ArrayList<>();
                ExcelUtils.excelRead(excel,ParkingBerthTemplateVO.class, voList);

                Assert.isFalse(CollectionUtil.isEmpty(voList), "文件不能为空");

                 // 保存逻辑
               // parkingBerthService.berthImport(voList);

                return Result.ok();
        }

3,导出接口

a,导出vo类

/**
 * 停车订单
 */
@Data
@SuperBuilder
@NoArgsConstructor
@Accessors(chain = true)
@ExcelIgnoreUnannotated
public class OrderParkingExportDTO {

    @ColumnWidth(10)
    @ExcelProperty(value = "ID" ,index = 0)
    private Long id;
    
    @ExcelProperty(value = "供应商ID",index = 1)
    private Long tenantId;

//    @ColumnWidth(100)
    @ExcelProperty(value = "订单号",index = 2)
    private String orderCode;

    @ExcelProperty(value = "停车场ID",index = 3)
    private Long parkingId;

    @ExcelProperty(value = "停车场名称",index = 4 )
    private String parkingName;

    @ExcelProperty(value = "客户ID",index = 5 )
    private Long customerId;

    @ExcelProperty(value = "无牌/有牌",index = 6 )
    private String hasPlateNoString;

    @ExcelProperty(value = "车牌",index = 7 )
    private String plateNo;

    private PlateColor plateColor;
    @ExcelProperty(value = "车牌颜色",index = 8 )
    private String plateColorString;

    public void dataProcessor(){
        if(hasPlateNo!= null){
            hasPlateNoString = hasPlateNo == true ? "有牌" : "无牌";
        }
        if(plateColor!= null){
            plateColorString = plateColor.getDesc();
        }
    }

}

b, 接口

        @ApiOperation(value = "列表导出", notes = "列表导出")
        @PostMapping("download")
        public void download(HttpServletResponse response,@RequestBody OrderParkingQueryVO vo, @ApiIgnore LoginSysUser loginSysUser) throws IOException {

                OrderParkingQueryDTO dto = OrderParkingConverter.INSTANCE.orderParking(vo, loginSysUser);
                List<OrderParking> list = orderParkingService.list(dto);
                List<OrderParkingExportDTO> data =  OrderParkingConverter.INSTANCE.entityToExportDto(list);
                data.forEach(item -> item.dataProcessor());
                String fileName = "列表导出";
                ExcelUtils.excelDownload(response,fileName,OrderParkingExportDTO.class,data);
        }
相关推荐
星如雨グッ!(๑•̀ㅂ•́)و✧3 分钟前
Spring Boot 2 快速教程:WebFlux处理流程(五)
java·spring boot·后端
小咕聊编程6 分钟前
【Java源码】基于SpringBoot+小程序的电影购票选座系统
java·spring boot·小程序
亦梦亦醒乐逍遥11 分钟前
【C++基础】字符串/字符读取函数解析
java·c++·算法
老马啸西风18 分钟前
IM 即时通讯系统-47-beardlessCat IM 使用netty开发分布式Im,提供分布netty集群解决方案
java·分布式·im
冬天vs不冷29 分钟前
SpringBoot源码解析(九):Bean定义接口体系
java·spring boot·rpc
CHANG_THE_WORLD36 分钟前
C++泛型编程指南08 auto decltype
java·jvm·c++
计算机-秋大田39 分钟前
基于SpringBoot的信息技术知识赛系统的设计与实现(源码+SQL脚本+LW+部署讲解等)
java·vue.js·spring boot·后端·课程设计
xidianjiapei00140 分钟前
如何在5步内使用 Spring AI 和 OpenAI 的 DALL-E 3 生成图像
java·人工智能·后端·spring·语言模型·openai
谦行42 分钟前
前端视角 Java Web 入门手册 2.3:Array
java·后端
customer081 小时前
【开源免费】基于SpringBoot+Vue.JS医院后台管理系统(JAVA毕业设计)
java·vue.js·spring boot·后端·开源