欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

快速入门,使用EasyExcel导入导出文件

程序员文章站 2024-03-21 13:01:58
...

maven依赖包

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>1.1.2-beta5</version>
</dependency>

<dependency>
     <groupId>org.projectlombok</groupId>
     <artifactId>lombok</artifactId>
</dependency>

一:集成Util

一般而言,除去业务逻辑操作之外,文件的导入导出操作应该是通用的,使用easyexcel进行导入导出操作,需要实体类继承BaseRowModel,因此我们可以基于easyexcel集成一个工具类:ExcelUtils

二:将前端上传的文件转换成对象列表

public static <T extends BaseRowModel> List<T> convertFile2ImportList(MultipartFile file, Class<T> clazz) {
        if (null == file) {
            throw new IllegalArgumentException("文件不能为空");
        }
        if (StringUtils.isBlank(file.getOriginalFilename())) {
            throw new IllegalArgumentException("文件名不能为空");
        }
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        if (!(Constants.EXCEL_03_SUFFIX.equals(suffix) || Constants.EXCEL_07_SUFFIX.equals(suffix))) {
            throw new IllegalArgumentException("文件格式不正确");
        }

        List<Object> objList;
        try {
            objList = EasyExcelFactory.read(file.getInputStream(), new Sheet(1, 1, clazz));
        } catch (IOException e) {
            throw new RuntimeException("", "");
        }
        List<T> list = objList.stream().map(obj -> (T) obj).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(list)) {
            throw new IllegalArgumentException("表格的数据不能为空");
        }
        if (list.size() > Constants.EXCEL_MAX_SIZE) {
            throw new IllegalArgumentException("表格的数据不能超过" + Constants.EXCEL_MAX_SIZE + "行");
        }

        return list;
    }

**关于EasyExcelFactory.read()这个方法,对于读取内容的大小有限制,一般不宜超过1000行,有时间再写关于导出的内容,本次就只写个能快速使用的实例。

三:导出数据

public static void exportExcel(Class<? extends BaseRowModel> clazz, String fileName, String sheetName, HttpServletResponse response, List<? extends BaseRowModel> data) {
    try {
        ExcelWriter writer = EasyExcelFactory.getWriter(response.getOutputStream());
        List<List<String>> head = new ArrayList<>();
        ExcelHeadProperty excelHeadProperty = new ExcelHeadProperty(clazz, head);

        Sheet sheet = new Sheet(1, 1);
        sheet.setHead(excelHeadProperty.getHead());
        sheet.setSheetName(sheetName);
        setSheetStyle(sheet);

        downloadExcel(writer, fileName, sheet, response, data);
    } catch (IOException e) {
        log.error("下载" + fileName + "失败: " + e);
        throw new RuntimeException(ErrCodeEnum.FILE_DOWNLOAD_FAIL);
    }
}

DownlodaExcel:

private static void downloadExcel(ExcelWriter writer, String fileName, Sheet sheet, HttpServletResponse response, List<? extends BaseRowModel> data) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        writer.write(data, sheet);
        writer.finish();
        response.getOutputStream().flush();
    }

SheetStyle:

private static void setSheetStyle(Sheet sheet) {
    sheet.setTableStyle(ExcelUtils.createTableStyle());
    sheet.setAutoWidth(true);

}

private static TableStyle createTableStyle() {
    TableStyle tableStyle = new TableStyle();
    Font headFont = new Font();
    headFont.setBold(true);
    headFont.setFontHeightInPoints((short) 13);
    headFont.setFontName("楷体");
    tableStyle.setTableHeadFont(headFont);
    tableStyle.setTableHeadBackGroundColor(IndexedColors.LIGHT_GREEN);


    Font contentFont = new Font();
    contentFont.setFontHeightInPoints((short) 12);
    contentFont.setFontName("楷体");
    tableStyle.setTableContentFont(contentFont);
    tableStyle.setTableContentBackGroundColor(IndexedColors.WHITE);

    return tableStyle;
}

四:导出文件到本地

public static void exportExcel2Local(List<? extends BaseRowModel> data, Class<? extends BaseRowModel> clazz, String fileName) {
    //去掉后缀
    String suffix = fileName.substring(fileName.lastIndexOf("."));
    fileName = fileName.replace(suffix, "");
    String current = DateUtils.format(new Date(), DateUtils.DATETIME_PATTERN);
    File dir = new File("D:\\uploadResult");
    if (!dir.exists()) {
        dir.mkdir();
    }
    File file = new File(fileName + "结果" + current + suffix);
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            log.error("创建文件失败");
            return;
        }
    }
    String path = dir.getPath() + "\\" + file.getPath();
    try (OutputStream os = new FileOutputStream(path)) {
        ExcelWriter writer = EasyExcelFactory.getWriter(os);
        Sheet sheet = new Sheet(1, 0, clazz);
        writer.write(data, sheet);
        writer.finish();
    } catch (IOException e) {
        log.error("批量导入失败: " + e);
    }
}
相关标签: EasyExcel