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

如何通过Office.js提取Word含合并单元格表格的JSON数据?

用Office.js提取带合并列的Word表格数据(表头关联JSON格式)

要解决合并列表头与数据的关联问题,核心是获取表头单元格的列跨度(colspan),再根据跨度对数据行的单元格分组,最终映射成预期的JSON结构。以下是具体实现步骤和代码:

核心思路

  1. 读取表格表头行,记录每个表头单元格的显示文本和列跨度(即该表头合并的列数)。
  2. 读取数据行的所有单元格文本,按表头的列跨度依次分组,将每组数据对应到对应表头。
  3. 把映射结果转换成目标JSON格式。

代码实现

async function extractMergedTableData() {
  await Word.run(async (context) => {
    // 获取当前选中的表格(也可通过table.getById等方式指定表格)
    const table = context.document.getSelection().parentTable;
    if (!table) {
      console.log("未选中表格");
      return;
    }

    // 加载表头行的单元格,包含文本和列跨度信息
    const headerRow = table.rows.getFirst();
    const headerCells = headerRow.cells;
    headerCells.load("text, range/columnCount");
    await context.sync();

    // 整理表头信息:[{text: '表头文本', span: 列跨度}]
    const headerInfo = [];
    for (let cell of headerCells.items) {
      headerInfo.push({
        text: cell.text.trim(),
        span: cell.range.columnCount
      });
    }

    // 加载数据行的单元格文本(此处假设仅一行数据,多行可循环处理)
    const dataRow = table.rows.getLast();
    const dataCells = dataRow.cells;
    dataCells.load("text");
    await context.sync();

    // 按表头跨度分组数据,生成目标结构
    const result = {};
    let dataIndex = 0;
    for (let header of headerInfo) {
      const dataGroup = [];
      // 取出对应跨度数量的数据单元格
      for (let i = 0; i < header.span; i++) {
        if (dataIndex < dataCells.items.length) {
          dataGroup.push(dataCells.items[dataIndex].text.trim());
          dataIndex++;
        }
      }
      result[header.text] = [dataGroup];
    }

    // 输出最终JSON
    console.log(JSON.stringify(result, null, 2));
    return result;
  }).catch((error) => {
    console.error("提取数据出错:", error);
  });
}

关键说明

  • cell.range.columnCount:Office.js中通过单元格的range对象获取合并列数,这是关联表头与数据的核心依据。
  • 多行数据适配:若表格有多行数据,只需循环遍历每一行数据,将每组数据追加到对应表头的数组中(例如result[header.text].push(dataGroup))。

示例输出

运行代码后将得到与预期一致的JSON结构:

{
  "Header 0,0": [["Cell 1.1", "Cell 2.1"]],
  "Header 3": [["Cell 3"]],
  "Header 4": [["Cell 4"]],
  "Header 5,6": [["Cell 5.1", "Cell 6.1"]]
}

内容的提问来源于stack exchange,提问作者Neer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 18:05:01