EasyExcel自定义多级表头导出

该博客介绍了一个用于通用Excel数据导出的接口实现,主要涉及阿里巴巴的EasyExcel库。通过业务编码和条件参数,接口能获取并导出指定模板的数据。首先,根据模板代码获取模板信息和数据源,然后查询表格列和数据。使用EasyExcel将数据写入Excel文件,自动生成表头并调整列宽。同时,展示了前端调用接口的代码示例。
摘要由CSDN通过智能技术生成

主要是封装好表头的list和数据的list。注意数据列的属性顺序和表头一致

package com.tgpms.web.common.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tgpms.web.excelTable.entity.ExcelTableColumn;
import com.tgpms.web.excelTable.entity.ExcelTableTemplate;
import com.tgpms.web.excelTable.service.IExcelTableColumnService;
import com.tgpms.web.excelTable.service.IExcelTableTemplateService;
import com.tgpms.web.system.entity.SmDatasource;
import com.tgpms.web.system.service.SmDatasourceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author jiangli
 * @since 2021/2/20 11:12
 * 通用Excel导出接口
 */
@Api(value = "ExcelController", tags = "通用Excel导出接口")
@RestController
@RequestMapping(value = "/ev/excel")
public class ExcelController {
    @Autowired
    private IExcelTableTemplateService templateService;
    @Autowired
    private IExcelTableColumnService columnService;
    @Autowired
    private SmDatasourceService smDatasourceService;

    @ApiOperation(value = "通过业务编码code导出数据", httpMethod = "GET")
    @GetMapping("/export")
    public void export(@RequestParam String code, @RequestParam String condition, HttpServletResponse response) throws IOException {
        ExcelTableTemplate one = templateService.getOne(new LambdaQueryWrapper<ExcelTableTemplate>().eq(ExcelTableTemplate::getCode, code));
        if (one == null) {
            return;
        }
        String ttId = one.getTtId();
        String dataSourceCode = one.getDataSourceCode();
        // 查询表格列
        List<ExcelTableColumn> excelTableColumns = columnService.list(new LambdaQueryWrapper<ExcelTableColumn>().eq(ExcelTableColumn::getTtId, ttId).orderByAsc(ExcelTableColumn::getOrderNo));
        Map<String, ExcelTableColumn> mapColumn = excelTableColumns.stream().collect(Collectors.toMap(ExcelTableColumn::getTcId, e -> e));
        List<ExcelTableColumn> leftList = excelTableColumns.stream().filter(e -> e.getLeaf().equals("1")).collect(Collectors.toList());
        List<List<String>> headList = new ArrayList<>();
        for (ExcelTableColumn excelTableColumn : leftList) {
            List<String> list = new ArrayList<>();
            headList(excelTableColumn,list,mapColumn);
            Collections.reverse(list);
            headList.add(list);
        }
        // 查询数据列表
        SmDatasource byDsCode = smDatasourceService.findByDsCode(dataSourceCode);
        if (null == byDsCode) {
            return;
        }
        String selectClause = byDsCode.getSelectClause().replace("@condition", condition);
        Map<String, String> params = new HashMap<>();
        params.put("sql", selectClause);
        List<Map<String, String>> list = smDatasourceService.executionSql(params);

        List<List<String>> data = new ArrayList<>();
        for (Map<String, String> map : list) {
            List<String> child = new ArrayList<>();
            for (ExcelTableColumn excelTableColumn : leftList) {
                String columnCode = excelTableColumn.getColumnCode();
                child.add(map.get(columnCode));
            }
            data.add(child);
        }

        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // 背景设置为白色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE1.getIndex());
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(headWriteCellStyle,new ArrayList<>());

//        String path = "C:\\Users\\admin\\Desktop\\test.xlsx";
//        EasyExcel.write(path).head(headList).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).sheet("sheet1").doWrite(data);
        // 设置 ContentType
        response.setContentType("application/vnd.ms-excel");
        // 设置字符集
        response.setCharacterEncoding("utf-8");
        // 防止中文乱码
        String fileName = URLEncoder.encode(one.getDescription(), "UTF-8");
        // 设置 header
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        // 写入 自定义表头
        EasyExcel.write(response.getOutputStream()).head(headList).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).sheet("sheet1").doWrite(data);
        // 写入 使用实体类的注解
        // EasyExcel.write(response.getOutputStream(), User.class).sheet("知识追寻者").doWrite(DataUtils.getUserData());
    }

    private void headList(ExcelTableColumn column, List<String> list, Map<String, ExcelTableColumn> mapColumn) {
        list.add(column.getLabel());
        String parentId = column.getParentId();
        if ("0".equals(parentId)) {
            return;
        }
        ExcelTableColumn tableColumn = mapColumn.get(parentId);
        headList(tableColumn,list,mapColumn);
    }

}

@Data
public class User {
​
    // id
    @ExcelProperty(index = 0,value = "编号")
    private Long id;
    // 名称
    @ExcelProperty(index = 1,value = "名称")
    private String name;
    // 创建时间
    @ExcelProperty(index = 2,value = "创建时间")
    private String createTime;
    // 描述
    @ExcelProperty(index = 3,value = "描述")
    private String description;
​
}

前端代码

 outExcel() {
      this.$message.success("正在下载,请稍候");
      const data = {code: this.code, condition: condition};
      this.axios.post('/ev/excel/export', qs.stringify(data), {responseType: 'blob'}).then(data => {
        if (data.status === 200) {
          const blob = new Blob([data.data]);
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          link.setAttribute("download", this.description + '.xlsx');
          document.body.appendChild(link);
          link.click();
        } else {
          this.$message.error("网络错误:" + data.status);
        }
      })
    },

 

可以使用EasyExcel来实现多级表头导出EasyExcel是一个基于Java的简单易用的Excel操作工具,支持大数据量的导入导出操作。 下面是一个示例代码,演示了如何实现多级表头导出: ```java // 创建一个excel写对象 ExcelWriter writer = EasyExcel.write("output.xlsx").build(); // 定义表头数据 List<List<String>> head = new ArrayList<>(); // 第一行表头 List<String> headRow1 = new ArrayList<>(); headRow1.add("一级表头"); headRow1.add("一级表头"); headRow1.add("一级表头"); head.add(headRow1); // 第二行表头 List<String> headRow2 = new ArrayList<>(); headRow2.add("二级表头"); headRow2.add("二级表头"); headRow2.add("二级表头"); head.add(headRow2); // 第三行表头 List<String> headRow3 = new ArrayList<>(); headRow3.add("三级表头"); headRow3.add("三级表头"); headRow3.add("三级表头"); head.add(headRow3); // 写入表头数据 Sheet sheet = new Sheet(1, 0); sheet.setHead(head); writer.write1(null, sheet); // 写入内容数据(省略) // 关闭excel写对象 writer.finish(); ``` 在上面的示例代码中,我们创建了一个ExcelWriter对象,并指定了输出文件名为"output.xlsx"。然后,我们定义了一个包含多级表头表头数据,每一级的表头都是一个List<String>。我们将这些表头数据添加到head列表中,然后使用Sheet对象将head列表设置为excel的表头。最后,调用writer的write1方法写入表头数据。 你可以根据需要修改示例代码中的表头数据,然后使用EasyExcel提供的其他方法写入内容数据。完成后,调用writer的finish方法关闭excel写对象即可。 希望对你有帮助!如果还有其他问题,请继续提问。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值