easyExcel 生成动态表头竟也如此简单!

在 Excel 中,多层级的动态表头(例如表头有三行)可以通过 EasyExcel 来实现。EasyExcel 支持多级表头的创建,通过 List<List<String>> 来定义每一行的表头内容。

下面是一个示例代码,展示如何生成一个具有三层表头的 Excel 文件:

1. 添加依赖

确保你已经添加了 EasyExcel 的依赖。如果你使用的是 Maven,可以在 pom.xml 文件中添加以下依赖:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.0.5</version>
</dependency>

2. 定义数据模型

假设我们有一个简单的数据模型 User

public class User {
    private String name;
    private Integer age;
    private String email;

    // Getters and Setters
}

3. 动态生成多层级的表头和数据

我们将使用一个方法来动态生成多层级的表头和数据:

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.*;

import java.util.ArrayList;
import java.util.List;

public class MultiLevelHeaderExcelExport {

    public static void main(String[] args) {
        // 动态生成多层级的表头
        List<List<String>> head = new ArrayList<>();
        List<String> headerRow1 = new ArrayList<>();
        headerRow1.add("基本信息");
        headerRow1.add("基本信息");
        headerRow1.add("基本信息");
        head.add(headerRow1);

        List<String> headerRow2 = new ArrayList<>();
        headerRow2.add("姓名");
        headerRow2.add("年龄");
        headerRow2.add("邮箱");
        head.add(headerRow2);

        List<String> headerRow3 = new ArrayList<>();
        headerRow3.add("Name");
        headerRow3.add("Age");
        headerRow3.add("Email");
        head.add(headerRow3);

        // 动态生成数据
        List<List<Object>> data = new ArrayList<>();
        List<Object> row1 = new ArrayList<>();
        row1.add("Alice");
        row1.add(30);
        row1.add("alice@example.com");
        List<Object> row2 = new ArrayList<>();
        row2.add("Bob");
        row2.add(25);
        row2.add("bob@example.com");
        data.add(row1);
        data.add(row2);

        // 导出到 Excel 文件
        String fileName = "multi_level_header_excel.xlsx";
        EasyExcel.write(fileName).head(head).sheet("Sheet1").doWrite(data);
    }
}

4. 运行程序

运行上述程序后,会在项目根目录下生成一个名为 multi_level_header_excel.xlsx 的 Excel 文件,其中包含多层级的表头和数据。

5. 自定义样式(可选)

如果需要自定义单元格样式,可以使用 WriteCellStyleHorizontalCellStyleStrategy。例如:

WriteCellStyle headWriteCellStyle = new WriteCellStyle();
headWriteCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
contentWriteCellStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

EasyExcel.write(fileName)
         .head(head)
         .registerWriteHandler(horizontalCellStyleStrategy)
         .sheet("Sheet1")
         .doWrite(data);
### 如何使用 EasyExcel 动态创建表格标题 为了动态创建表格标题,可以借助于 `EasyExcel` 提供的强大功能。此工具允许开发者定义复杂的表头逻辑,在运行时根据实际需求调整列的数量及其名称。 #### 定义动态表头类 首先,需构建一个能够适应不同场景下变化的实体模型。该模型应具备灵活性以便容纳未知数量的字段以及对应的属性名作为未来显示在 Excel 中的列标题[^1]。 ```java import com.alibaba.excel.annotation.ExcelProperty; public class DynamicHeadData { @ExcelProperty("固定列") // 这里设置了一个静态列用于示范, 实际应用中可全部设为动态 private String fixedColumn; public void setFixedColumn(String fixedColumn){ this.fixedColumn = fixedColumn; } } ``` 对于完全动态的情况,则不需要上述注解方式指定具体哪一列为定值;而是通过编程手段向 `WriteSheet` 添加额外参数来控制每行记录前几项之外的内容布局。 #### 编写服务层方法实现业务逻辑 接下来编写一段程序片段用来说明怎样基于某些条件决定最终要呈现出来的表单样式: ```java import com.alibaba.excel.EasyExcel; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import org.springframework.stereotype.Service; @Service public class ExportService { public void exportDynamicHeaderFile(List<Map<String,Object>> dataList, List<List<String>> headList ,String fileName) { try{ // 构建 writer 属性并指明目标路径与文件名 File file = new File(fileName); // 使用 EasyExcel 的 write 方法开始写入过程 EasyExcel.write(file).head(headList).sheet("模板").doWrite(dataList.stream() .map(entry -> entry.values().toArray(new Object[0])) .collect(Collectors.toList())); }catch(Exception e){ log.error(e.getMessage(),e); } } } ``` 这段代码展示了如何接收两个列表形式的数据源:一个是包含多级或多变表头信息的二维数组 `headList` ,另一个则是待填充到单元格中的键值对集合 `dataList`. 接着调用了 `write()` 函数启动导出流程,并传入了自定义好的头部描述和工作簿标签页的名字 "模板"[^2]. #### 调用示例 最后给出一个简单的例子展示如何调用上面的服务函数完成整个操作: ```java @RestController @RequestMapping("/export") public class ExportController { @Autowired private ExportService exportService; @GetMapping("/dynamic-head-excel") public ResponseEntity<Void> generateDynamicHeadExcel() throws IOException { List<List<String>> heads = Arrays.asList( Arrays.asList("姓名", "年龄"), Arrays.asList("爱好","职业")); List<Map<String, Object>> dataRecords = new ArrayList<>(); Map<String, Object> recordOne = Maps.newHashMap(); recordOne.put("姓名", "张三"); recordOne.put("年龄", 30L); recordOne.put("爱好", "篮球"); recordOne.put("职业", "工程师"); dataRecords.add(recordOne); exportService.exportDynamicHeaderFile(dataRecords,heads,"/tmp/dynamic_head.xlsx"); return ResponseEntity.ok().build(); } } ``` 在这个 RESTful Web Service 控制器内,当接收到 `/export/dynamic-head-excel` 请求时就会触发生成具有特定结构化顶部区域的新文档实例[^3].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值