You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ExcelJS中为列标题上方添加统一工作表标题?

ExcelJS 实现双工作表首行标题+列标题+数据方案

核心思路是避开columns属性的自动标题生成逻辑,手动控制行的顺序:先写首行标题,再写列标题行,最后填充数据。以下是可直接运行的代码示例:

步骤1:安装依赖

npm install exceljs

步骤2:完整实现代码

const ExcelJS = require('exceljs');

// 初始化工作簿
const workbook = new ExcelJS.Workbook();

// 定义通用配置(可根据业务调整)
const globalTitle = "XX公司员工数据报表";
const columnHeaders = ["ID", "姓名", "部门", "入职日期", "薪资"];
const sampleData = [
  { id: 1, name: "张三", dept: "技术部", hireDate: new Date(2020, 5, 10), salary: 8000 },
  { id: 2, name: "李四", dept: "市场部", hireDate: new Date(2021, 2, 15), salary: 7500 },
  { id: 3, name: "王五", dept: "人事部", hireDate: new Date(2019, 10, 20), salary: 6800 }
];
const columnConfigs = [
  { key: 'id', width: 8 },
  { key: 'name', width: 12 },
  { key: 'dept', width: 12 },
  { key: 'hireDate', width: 15, type: 'date', numFmt: 'yyyy-mm-dd' },
  { key: 'salary', width: 10, type: 'number', numFmt: '#,##0' }
];

// 封装工作表创建逻辑,避免重复代码
function buildSheet(sheetName) {
  const sheet = workbook.addWorksheet(sheetName);

  // 1. 设置首行标题(合并单元格+样式)
  const titleRow = sheet.getRow(1);
  titleRow.getCell(1).value = globalTitle;
  const lastCol = String.fromCharCode(64 + columnHeaders.length); // 自动计算最后一列字母
  sheet.mergeCells(`A1:${lastCol}1`);
  titleRow.font = { bold: true, size: 14 };
  titleRow.alignment = { horizontal: 'center' };

  // 2. 设置第二行列标题(样式优化)
  const headerRow = sheet.getRow(2);
  headerRow.values = columnHeaders;
  headerRow.font = { bold: true };
  headerRow.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFCCCCCC' } };

  // 3. 配置列属性(宽度、数据格式等)
  sheet.columns = columnConfigs;

  // 4. 填充数据行
  sampleData.forEach(item => sheet.addRow(item));
}

// 创建两个工作表
buildSheet("技术&市场部数据");
buildSheet("人事&行政部数据");

// 导出文件
workbook.xlsx.writeFile('员工报表.xlsx')
  .then(() => console.log('报表生成成功'))
  .catch(err => console.error('生成失败:', err));

关键说明

  1. 为什么之前的方法无效?

    • headerFooter是页面打印的页眉页脚,不是工作表内容的首行;
    • 先插入行再设置columns时,columns默认会把列标题覆盖到第一行,所以必须手动控制列标题的位置。
  2. 可自定义的点:

    • 标题的合并范围、样式;
    • 列标题的背景色、字体;
    • 列的宽度、数据格式化规则;
    • 数据来源可替换为业务接口返回值。

内容的提问来源于stack exchange,提问作者FE-P

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 15:16:14