当导出 Excel 时,如何结合 EasyExcel 实现脱敏?

解读

国内金融、运营商、政企项目普遍要求“敏感数据不出域”,导出 Excel 时必须对手机号、身份证、银行卡、地址等字段做脱敏。
Struts 2 的 Action 作为控制器,负责把数据库结果集转成 VO 列表,再通过 EasyExcel 写出到 ServletOutputStream。
因此脱敏动作必须放在“数据写出前一刻”完成,既不影响数据库原始数据,也不污染业务 Service,还要保证分页大文件的内存安全。

知识点

  1. EasyExcel 写出生命周期:WriteHandler 接口 → CellWriteHandler 在单元格写出前触发,可对 value 做最后修正。
  2. Struts 2 文件下载固定套路:
    • Action 中 HttpServletResponse response = ServletActionContext.getResponse();
    • 设置 Content-Disposition=attachment;filename*=utf-8''xxx.xlsx 兼容中文。
    • 禁止 struts.xml 中配置 <result type="stream">,否则会出现双响应提交。
  3. 脱敏策略:
    • 正则替换(手机号 1([0-9]{2})[0-9]{4}([0-9]{4}) → $1****$2)
    • 注解驱动(自定义 @Sensitive(type=SensitiveTypeEnum.MOBILE))
    • 字段级 SPI(实现 Converter<String> 接口,只对指定列生效)。
  4. 性能与安全:
    • 使用 EasyExcel.write(outputStream, clazz).registerWriteHandler(new SensitiveCellWriteHandler()).build() 实现流式写出,内存恒定 1M 左右。
    • 敏感规则放在服务端本地配置中心(Nacos、Apollo),禁止前端传规则,防止绕过。
    • 若数据量超过 5W 行,启用 SXSSF 模式并设置 rowAccessWindowSize=1000,防止 Full GC。

答案

  1. 定义脱敏注解
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Sensitive {
    SensitiveTypeEnum value();
}
  1. 实现列级写处理器
public class SensitiveCellWriteHandler implements CellWriteHandler {
    @Override
    public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
                                Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        if (isHead) return;
        Field field = head.getField();
        Sensitive anno = field.getAnnotation(Sensitive.class);
        if (anno != null) {
            String origin = cell.getStringCellValue();
            String masked = SensitiveRuleContainer.mask(anno.value(), origin);
            cell.setCellValue(masked);
        }
    }
}
  1. Action 代码(Struts 2 方式)
public class ExportAction extends ActionSupport {
    private UserService userService; // Spring 注入
    public String export() throws IOException {
        List<UserVO> data = userService.listAll(); // 已做分页
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("用户数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        EasyExcel.write(response.getOutputStream(), UserVO.class)
                 .registerWriteHandler(new SensitiveCellWriteHandler())
                 .sheet("用户")
                 .doWrite(data);
        return NONE; // 告诉 Struts 2 不再做结果转发
    }
}
  1. 在 VO 字段上标记
public class UserVO {
    @Sensitive(SensitiveTypeEnum.MOBILE)
    private String mobile;

    @Sensitive(SensitiveTypeEnum.ID_CARD)
    private String idCard;
}
  1. 权限二次校验
    在 SensitiveCellWriteHandler 里先调用 SecurityContext.hasPermission("DATA_EXPORT_SENSITIVE"),若无权限则直接 throw new AppException("无导出明文权限");,防止水平越权。

拓展思考

  1. 多租户 SaaS 场景:脱敏规则与租户编号绑定,EasyExcel 写出前把 TenantContextHolder.getTenantId() 作为 key 去捞规则,实现租户级差异化脱敏。
  2. 导出模板复用:把 SensitiveCellWriteHandler 与 LongestMatchColumnWidthStyleStrategy 一起注册,形成公司级 Excel 导出 starter,所有 Struts / Spring Boot 项目一键引用。
  3. 反向导入验重:用户上传 Excel 做数据回补时,先把脱敏字段按掩码正则还原成通配符(如 138****1234 → 138____1234),再用数据库 LIKE 模糊匹配,实现不暴露明文前提下的唯一性校验。