使用EasyExcel根据模板导出文件

概要

在企业级应用开发中,Excel数据导出是一个常见的需求。本文实现一个基于阿里巴巴EasyExcel库实现的根据模板导出文件的工具类,它通过预定义的Excel模板来生成结构化的数据报表,提高了导出功能的开发效率和灵活性。

工具类核心功能

该ExportUtil工具类主要提供以下功能:

  1. 模板化导出:基于预定义的Excel模板填充数据
  2. 灵活数据支持:支持列表数据和离散对象数据的填充
  3. 自动响应设置:自动处理HTTP响应头,实现文件下载
  4. 异常处理:统一的异常处理机制,确保导出过程稳定性

核心代码解析

类结构与常量定义

@Slf4j
@Component
public class ExportUtil {
    public static final String TEMPLATE_ROOT_PATH = "template";
    public static final String EXCEL_POSTFIX = "." + CommonConst.EXCEL_TYPE_XLSX;
    // ...
}

使用Lombok注解简化日志管理。定义了模板根路径和Excel文件后缀常量(可自行定义)。

模板导出核心方法

public static void downloadExcelByTemplate(String templatePath, String fileName, 
                                         List<?> list, Object obj) {
    String templateFileName = TEMPLATE_ROOT_PATH + File.separator + templatePath;
    download(fileName + EXCEL_POSTFIX, outputStream -> {
        try (ExcelWriter excelWriter = EasyExcel.write(outputStream)
                .withTemplate(ExportUtil.class.getClassLoader()
                .getResourceAsStream(templateFileName)).build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            excelWriter.fill(list, fillConfig, writeSheet);
            excelWriter.fill(obj, fillConfig, writeSheet);
        } catch (Exception e) {
            log.error("Writing template failed:{}", e.getMessage());
            throw new BusinessException(BusinessExceptionEnum.EXPORT_FAILED);
        }
    });
}

该方法接收四个参数:

  1. templatePath: 模板文件路径
  2. fileName: 导出文件名(不含后缀)
  3. list: 列表数据(用于填充模板中的表格区域)
  4. obj: 离散数据(用于填充模板中的单个字段)

文件下载处理

public static void download(String fileName, Consumer<ServletOutputStream> write) {
    HttpServletResponse response = getHttpServletResponse(fileName);
    ServletOutputStream outputStream;
    try {
        outputStream = response.getOutputStream();
    } catch (IOException e) {
        log.error("Failed to read response and write stream:{}", e.getMessage());
        throw new BusinessException(BusinessExceptionEnum.EXPORT_FAILED);
    }
    write.accept(outputStream);
}

封装了文件下载的通用逻辑,接收一个文件名和一个用于写入输出流的Consumer函数式接口。

HTTP响应设置

@SneakyThrows
public static HttpServletResponse getHttpServletResponse(String fileName) {
    ServletRequestAttributes servletRequestAttributes = 
        (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    if (servletRequestAttributes == null || servletRequestAttributes.getResponse() == null) {
        log.error("Unable to obtain HttpServletResponse.");
        throw new BusinessException(BusinessExceptionEnum.EXPORT_FAILED);
    }
    HttpServletResponse res = servletRequestAttributes.getResponse();
    res.setContentType("application/octet-stream; charset=" + StandardCharsets.UTF_8);
    res.setHeader("Content-disposition", "attachment;filename=" + 
        URLEncoder.encode(fileName, StandardCharsets.UTF_8) + ";" + 
        "filename*=utf-8''" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
    return res;
}

负责设置HTTP响应头,包括内容类型和内容处置头,确保浏览器正确处理文件下载。使用URLEncoder对文件名进行编码,解决中文文件名乱码问题。

文件下载处理

使用示例

1. 准备Excel模板

在resources/template目录下创建模板文件,例如user_template.xlsx。在模板中使用{}占位符表示离散数据,使用{.}表示列表数据。

2. 调用导出方法

// 准备数据
UserInfo userInfo = new UserInfo("张三", "技术部");
List<Order> orders = Arrays.asList(
    new Order("订单001", new Date(), 2999.0),
    new Order("订单002", new Date(), 3999.0)
);

// 执行导出
ExportUtil.downloadExcelByTemplate("user_template.xlsx", "用户订单", orders, userInfo);
### EasyExcel 使用模板导出数据示例 #### 准备工作 为了实现基于模板Excel 文件导出功能,需先准备好所需的依赖项以及模板文件。确保 Maven 项目的 `pom.xml` 中已引入 EasyExcel 库: ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>3.3.4</version> </dependency> ``` 此外,准备一个 Excel 模板文件作为基础,在此模板上动态填充所需的数据。 #### 编写 Java 代码 下面是一个完整的例子展示如何利用 EasyExcel 实现根据模板导出数据的功能: ```java import com.alibaba.excel.EasyExcel; import java.util.ArrayList; import java.util.List; public class TemplateExportExample { public static void main(String[] args) { String templateFilePath = "path/to/your/template.xlsx"; String exportFilePath = "path/to/exported/file.xlsx"; List<UserData> dataList = new ArrayList<>(); // 填充数据列表... EasyExcel.write(exportFilePath) .withTemplate(templateFilePath) .sheet() .doWrite(dataList); } } ``` 其中 `UserData` 是自定义的数据类,用于表示要填入模板的具体记录。假设有一个简单的用户信息表,则可以这样定义这个类: ```java // 用户信息实体类 class UserData { @ExcelProperty("姓名") private String name; @ExcelProperty("年龄") private int age; // Getters and Setters omitted for brevity. } ``` 通过上述方式,能够轻松地按照既定格式向指定位置插入相应的字段值[^2]。 #### 关键配置与注意事项 当使用带有占位符或其他特殊标记的复杂模板时,可能还需要额外设置一些参数来适配具体场景下的需求。比如调整样式、处理日期时间格式化等问题都可以借助于 EasyExcel 提供的相关 API 来完成。 对于更复杂的业务逻辑,如分页读取数据库并逐步写出至 Excel 文档等情况,建议查阅官方文档获取更多指导和支持[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值