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

Word加载项:如何通过Office.js API在OOXML中包含自定义属性

问题原因与解决方案

核心原因

context.document.body.getOoxml()仅返回Word文档正文区域的OOXML(对应docx压缩包内的word/document.xml文件),而你通过context.document.properties.customProperties添加的自定义属性属于文档级元数据,存储在docx压缩包的docProps/custom.xml中,和正文OOXML完全分离,因此直接导出正文OOXML无法包含这些属性。

可行解决方案

方案1:获取完整文档的OOXML(包含所有元数据)

如果需要导出包含自定义属性的完整文档内容,应使用Office.js的完整文档获取API,而非仅导出正文。示例代码如下:

// 获取完整文档(二进制格式)
Office.context.document.getFileAsync(Office.FileType.Compressed, { sliceSize: 65536 }, function (result) {
  if (result.status === Office.AsyncResultStatus.Succeeded) {
    var file = result.value;
    var slices = [];
    var sliceCount = file.sliceCount;

    // 读取所有文件切片
    for (var i = 0; i < sliceCount; i++) {
      file.getSliceAsync(i, function (sliceResult) {
        if (sliceResult.status === Office.AsyncResultStatus.Succeeded) {
          slices.push(sliceResult.value.data);
          if (slices.length === sliceCount) {
            // 拼接切片为完整docx文件Blob
            var blob = new Blob(slices, { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" });
            // 该Blob包含所有自定义属性,可直接保存为文件或解析元数据部分
            file.closeAsync();
          }
        } else {
          file.closeAsync();
          console.error("读取切片失败", sliceResult.error);
        }
      });
    }
  } else {
    console.error("获取文档失败", result.error);
  }
});

方案2:单独读取自定义属性,按需结合正文OOXML

如果仅需正文OOXML搭配自定义属性数据,可以先单独提取属性,再根据需求结合两者:

// 加载并获取所有自定义属性
await context.document.properties.customProperties.load();
await context.sync();

// 整理自定义属性为键值对
const customProps = {};
for (let i = 0; i < context.document.properties.customProperties.items.length; i++) {
  const prop = context.document.properties.customProperties.items[i];
  customProps[prop.key] = prop.value;
}

// 获取正文OOXML
const bodyOoxmlResult = context.document.body.getOoxml();
await context.sync();
const bodyOoxml = bodyOoxmlResult.value;

// 后续可将bodyOoxml与customProps一同存储,使用时再合并到完整文档结构中

关于context.document.save()的说明

调用save()会将自定义属性持久化到文档中,但它不会改变getOoxml()仅返回正文内容的特性——因为自定义属性的存储位置和正文完全独立。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 11:44:56