【问题标题】:Word Add-in - How to read custom document propertyWord 加载项 - 如何读取自定义文档属性
【发布时间】:2017-06-27 19:06:09
【问题描述】:

我正在使用 Office JS API 开发 Word 插件。

目前我可以通过以下方式向 Word 文档添加自定义属性:

context.document.properties.load();
context.document.properties.customProperties.add("file-name-prop", "my file name");

如果我随后下载该文件,我可以在压缩 docx 内的“custom.xml”文件中看到该属性。

但我无法读取该属性。

我正在尝试这样做:

context.document.properties.load();
var filenameProp = context.document.properties.customProperties.getItemOrNullObject("file-name-prop");
if (filenameProp) {
    // use filenameProp.value
} else {
    // ignore, property not set
}

这样做时,我收到以下错误:

code : "PropertyNotLoaded"
message : "The property 'type' is not available. Before reading the property's value, call the load method on the containing object and call "context.sync()" on the associated request context."
name : "OfficeExtension.Error"

读回属性的正确方法是什么?

(我在用这个office js:appsforoffice.microsoft.com/lib/beta/hosted/office.js

【问题讨论】:

    标签: ms-office office365 office-js office-addins


    【解决方案1】:

    可能是您没有包含您的代码部分,但我没有看到您同步上下文的任何地方。您提供的错误消息表明相同:“在读取属性值之前,调用包含对象的加载方法并在关联的请求上下文中调用“context.sync()”。”。看起来您完全或部分缺少context.sync()。同步上下文后,您应该能够获取自定义属性。例如,要创建自定义属性,代码应类似于 ...

    function setProperty (prop_name, prop_value) {
      Word.run(function (context) {
        context.document.properties.customProperties.add(prop_name, prop_value);
        return context.sync()
          .catch(function (e) {
            console.log(e.message);
          })
      })
    }
    

    当您需要获取属性时,代码仍然使用“同步”来使属性可用。例如,要获取自定义属性,代码应类似于 ...

    function getProperties() { 
        Word.run(function (context) {
            var customDocProps = context.document.properties.customProperties;
            context.load(customDocProps);
            return context.sync()
                .then(function () {
                    console.log(customDocProps.items.length);
                 })
         })
    }
    

    【讨论】:

    • 您的回答是正确的,但为了实际读取属性值,我还必须使上下文“加载”实际属性。我将其作为单独的答案发布以供将来参考。
    【解决方案2】:

    Slava 的回答是对的,但要实际读取属性值,我还必须实际加载那个值,我觉得这很令人费解,但是...

    最终工作代码(借用 Slava 的示例):

    function getPropertyValue() { 
      Word.run(function (context) {
        var customDocProps = context.document.properties.customProperties;
        // first, load custom properties object
        context.load(customDocProps);
        return context.sync()
          .then(function () {
            console.log(customDocProps.items.length);
            // now load actual property
            var filenameProp = customDocProps.getItemOrNullObject("file-name-prop");
            context.load(filenameProp);
            return context.sync()
              .then(function () {
                console.log(filenameProp.value);
              });
          });
      });
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多