wangwang
wangwang
文章32
标签32
分类5
Easypoi导入导出Excel

Easypoi导入导出Excel

官网地址

Easypoi开发文档

导出实例

// 导出导入实体类
@Data
public class R implements Serializable, IExcelModel, IExcelDataModel {

    private static final long serialVersionUID = -3099653964677586050L;

    private int rowNum;

    private String errorMsg;

    @Excel(name = "导入字段", width = 20)
    @NotBlank
    private String field;


    @Override
    public Integer getRowNum() {
        return rowNum;
    }

    @Override
    public void setRowNum(Integer rowNum) {
        this.rowNum = rowNum;
    }

    @Override
    public String getErrorMsg() {
        return errorMsg;
    }

    @Override
    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }
}
    public void exportExcel(HttpServletResponse response, HttpServletRequest request) throws IOException {
        Workbook workbook;
        String filename = "导出.xlsx";
        ExportParams exportParams = new ExportParams();
        exportParams.setDictHandler(deviceTypeHandler);
        workbook = ExcelExportUtil.exportExcel(exportParams, R.class, new ArrayList<>());
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=utf-8" + URLEncoder.encode(filename, "UTF-8"));
        response.setCharacterEncoding("UTF-8");
        workbook.write(response.getOutputStream());
    }

导入实例

public Result importExcel(MultipartFile file) throws Exception {
        ImportParams importParams = new ImportParams();
        importParams.setNeedVerify(true);
        importParams.setDictHandler(deviceTypeHandler);
        ExcelImportResult<R> result = ExcelImportUtil.importExcelMore(file.getInputStream(), R.class, importParams);
        // 错误打印业务逻辑
        if (result.isVerifyFail()) {
            return Result.error(result.getFailList().stream().map(item -> "第" + item.getRowNum() + "行报错,错误信息:" + item.getErrorMsg()).collect(Collectors.joining(",")));
        } else {
               // 导入数据处理业务逻辑
            return Result.success("导入成功");
        }
    }

最后

最近要写导出导入,长时间没用导致都忘了写法了,特此记录一下,方便日后使用!

本文作者:wangwang
本文链接:https://www.wangwangit.com/Excel%E5%AF%BC%E5%87%BA%E5%AF%BC%E5%85%A5%E5%AE%9E%E7%8E%B0/
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可