【EasyExcel】使用技巧


前言

【EasyExcel】的使用技巧,随时间推移进行更新:

  • 2023-12-26——【使excel中的公式生效】
  • 2023-12-28——【ExportUtil,通用方法导出Excel】
  • 2024-07-09——【ExportUtil,增加合并列操作策略】

提示:以下是本篇文章正文内容

一、使excel中的公式生效

ExcelWriter excelWriter = EasyExcel.write(out).withTemplate(in).build();
// 导出逻辑
…………
…………
// 使excel中的公式生效
excelWriter.writeContext().writeWorkbookHolder().getWorkbook().setForceFormulaRecalculation(true);

代码讲解
首先获取excelWriter ,然后导出,然后最后通过excelWriter 获取到workbook,然后设置对应的参数为true,即可使excel模板中原有的公式生效,如sum(a1:a5)之类的原公式。

二、【ExportUtil】:通用方法导出Excel

getOutputStream()方法:

    /**
     * 导出文件时为Writer生成OutputStream.
     *
     * @param fileName 文件名
     * @param response response
     * @return 输出流
     */
    public static OutputStream getOutputStream(String fileName, HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "no-store");
            response.addHeader("Cache-Control", "max-age=0");
            return response.getOutputStream();
        } catch (Exception e) {
            throw new ServiceException(ResultCode.FAILURE, "导出失败");
        }
    }

1.导出模板

模板是存在于resource目录下的固定的模板文件

    /**
     * 下载模板
     *
     * @param response response
     * @param fileName 模板文件名称
     */
    public static void downloadTemplate(HttpServletResponse response, String fileName) {
        try (OutputStream out = getOutputStream(fileName, response);
             InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("template/" + fileName + ".xlsx");
             ExcelWriter excelWriter = EasyExcel.write(out).withTemplate(in).build()) {
            excelWriter.finish();
        } catch (Exception e) {
            log.error("模板下载失败:{}", e.getLocalizedMessage());
            throw new ServiceException(ResultCode.FAILURE, "模板下载失败");
        }
    }

2.导出excel,使用模板导出

模板是存在于resource目录下的固定的模板文件,使用对应模板的数据进行导出

    /**
     * 导出excel,使用模板
     *
     * @param response     response
     * @param templateName 模板文件名
     * @param data         数据
     * @param exportName   导出文件名
     */
    public static void excelExportByTemplate(HttpServletResponse response, String templateName, Object data, String exportName) {
        try (OutputStream out = getOutputStream(exportName, response);
             InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("template/" + templateName + ".xlsx")) {
            EasyExcel.write(out).withTemplate(in).sheet()
                    .registerWriteHandler(ExportUtil.getStyleStrategy())
                    .doFill(data);
        } catch (Exception e) {
            log.error("导出失败:{}", e.getLocalizedMessage());
            throw new ServiceException(ResultCode.FAILURE, "导出失败");
        }
    }

3.导出excel,使用注解导出

使用easyExcel提供的注解标注dto后,进行导出

    /**
     * 导出excel,使用注解
     *
     * @param response response
     * @param fileName 文件名
     * @param data     数据
     * @param clazz    实体类
     */
    public static void excelExportByAnnotation(HttpServletResponse response, String fileName, List<?> data, Class<?> clazz) {
        try (OutputStream out = getOutputStream(fileName, response)) {
            EasyExcel.write(out, clazz).sheet()
                    .registerWriteHandler(ExportUtil.getStyleStrategy()) // getStyleStrategy()是下一个代码块中的导出策略
                    .doWrite(data);
        } catch (Exception e) {
            log.error("导出失败:{}", e.getLocalizedMessage());
            throw new ServiceException("导出失败");
        }
    }
    /**
     * 导出策略
     */
    public static HorizontalCellStyleStrategy getStyleStrategy() {
        // 头的策略  样式调整
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // 头背景色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        WriteFont headWriteFont = new WriteFont();
        // 头字号
        headWriteFont.setFontHeightInPoints((short) 15);
        // 字体样式
        headWriteFont.setFontName("宋体");
        headWriteCellStyle.setWriteFont(headWriteFont);
        // 自动换行
        headWriteCellStyle.setWrapped(false);
        // 设置细边框
        headWriteCellStyle.setBorderBottom(BorderStyle.THIN);
        headWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        headWriteCellStyle.setBorderRight(BorderStyle.THIN);
        headWriteCellStyle.setBorderTop(BorderStyle.THIN);
        // 设置边框颜色
        headWriteCellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        headWriteCellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
        headWriteCellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        headWriteCellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
        // 水平对齐方式/垂直对齐方式
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        ///
        // 内容的策略 宋体
        WriteCellStyle contentStyle = new WriteCellStyle();
        // 设置垂直居中
        contentStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 设置水平居中
        contentStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        WriteFont contentWriteFont = new WriteFont();
        // 内容字号
        contentWriteFont.setFontHeightInPoints((short) 12);
        // 字体样式
        contentWriteFont.setFontName("宋体");
        contentStyle.setWriteFont(contentWriteFont);
        // 设置细边框
        contentStyle.setBorderBottom(BorderStyle.THIN);
        contentStyle.setBorderLeft(BorderStyle.THIN);
        contentStyle.setBorderRight(BorderStyle.THIN);
        contentStyle.setBorderTop(BorderStyle.THIN);
        // 设置边框颜色
        contentStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        contentStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
        contentStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        contentStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
        // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
        return new HorizontalCellStyleStrategy(headWriteCellStyle, contentStyle);
    }

4.使用注解导出,且使用合并策略

使用easyExcel提供的注解标注dto后,进行导出,并使用合并策略

public static void excelExportByAnnotationAndMergeColumn(HttpServletResponse response, String fileName, List<?> data, Class<?> clazz, ExcelStringMergeStrategy strategy) {
        try (OutputStream out = getOutputStream(fileName, response)) {
            EasyExcel.write(out, clazz).sheet()
                    .registerWriteHandler(strategy)
                    .doWrite(data);
        } catch (Exception e) {
            log.error("导出失败:{}", e.getLocalizedMessage());
            throw new ServiceException("导出失败");
        }
    }

合并策略,上面的方法中最后一个参数,可以使用:ExcelStringMergeStrategy.commonMergeStrategy()代入,默认合并第一列,从第二行开始合并,也可以自己指定对应的列和行然后合并。

/**
 * 仅针对字符串单元格进行合并
 */
@Data
public class ExcelStringMergeStrategy implements CellWriteHandler {

    /**
     * 要合并的列索引
     */
    private int[] mergeColumnIndex;

    /**
     * 从第几行开始合并
     */
    private int mergeRowIndex;

    /**
     * 全参构造
     *
     * @param mergeColumnIndex 要合并的列索引
     * @param mergeRowIndex    从第几行开始合并
     */
    public ExcelStringMergeStrategy(int[] mergeColumnIndex, int mergeRowIndex) {
        this.mergeColumnIndex = mergeColumnIndex;
        this.mergeRowIndex = mergeRowIndex;
    }

    /**
     * 默认合并第一列,从第二行开始合并
     *
     * @return ExcelStringMergeStrategy
     */
    public static ExcelStringMergeStrategy commonMergeStrategy() {
        return new ExcelStringMergeStrategy(new int[]{0}, 1);
    }

    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        // 当前行
        int curRowIndex = cell.getRowIndex();
        // 当前列
        int curColIndex = cell.getColumnIndex();

        if (curRowIndex >= mergeRowIndex) {
            for (int columnIndex : mergeColumnIndex) {
                if (curColIndex == columnIndex) {
                    mergeWithPrevRow(writeSheetHolder, cell, curRowIndex, curColIndex);
                    break;
                }
            }
        }
    }

    /**
     * 当前单元格向上合并
     *
     * @param writeSheetHolder 当前操作sheet
     * @param cell             当前单元格
     * @param curRowIndex      当前行
     * @param curColIndex      当前列
     */
    private void mergeWithPrevRow(WriteSheetHolder writeSheetHolder, Cell cell, int curRowIndex, int curColIndex) {
        // 获取上一个单元格
        Cell preCell = cell.getSheet().getRow(curRowIndex - 1).getCell(curColIndex);
        // 获取当前、上一个单元格类型
        CellType thisCellType = cell.getCellType();
        CellType preCellType = preCell.getCellType();

        // 类型不一致,不合并
        if (thisCellType != preCellType) {
            return;
        }

        // 如果当前单元格不为字符串
        if (thisCellType != CellType.STRING) {
            return;
        }

        // 【只针对字符串单元格数据进行合并】:
        // 将当前单元格数据与上一个单元格数据比较
        boolean dataBool = StrUtil.equals(cell.getStringCellValue(), preCell.getStringCellValue());

        // 如果数据一致,合并
        if (dataBool) {
            Sheet sheet = writeSheetHolder.getSheet();
            List<CellRangeAddress> mergeRegions = sheet.getMergedRegions();
            boolean isMerged = false;
            for (int i = 0; i < mergeRegions.size() && !isMerged; i++) {
                CellRangeAddress cellRangeAddr = mergeRegions.get(i);
                // 若上一个单元格已经被合并,则先移出原有的合并单元,再重新添加合并单元
                if (cellRangeAddr.isInRange(curRowIndex - 1, curColIndex)) {
                    sheet.removeMergedRegion(i);
                    cellRangeAddr.setLastRow(curRowIndex);
                    sheet.addMergedRegion(cellRangeAddr);
                    isMerged = true;
                }
            }
            // 若上一个单元格未被合并,则新增合并单元
            if (!isMerged) {
                CellRangeAddress cellRangeAddress = new CellRangeAddress(curRowIndex - 1, curRowIndex, curColIndex, curColIndex);
                sheet.addMergedRegion(cellRangeAddress);
            }
        }
    }
}

总结

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
EasyExcel是阿里巴巴开源的一个excel处理框架,使用简单且节省内存。它适合处理大数据量的Excel,不像之前的Excel解析框架将数据一次性加载到内存中,而是从磁盘上逐行读取数据并解析。它重写了poi对07版本Excel的解析,在处理大数据时不容易发生内存溢出。EasyExcel可以用于数据导入、数据导出以及数据传输等场景。在使用EasyExcel时,可以使用注解来自定义表头、选择excel中的顺序、忽略不需要导出的属性、进行日期格式转换,以及设置行宽等。官方文档提供了更详细的使用说明。 在实际应用中,可以使用@ExcelIgnore注解来标记不需要导出的多余属性,这样可以避免导出不需要的字段。另外,可以使用@DateTimeFormat注解来进行日期格式转换,使用@ColumnWidth注解来设置行宽。 总的来说,EasyExcel是一个方便易用的excel处理框架,可以帮助我们简化Excel的处理操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [EasyExcel使用教程](https://blog.csdn.net/tttalk/article/details/123379580)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值