首页 文章

Word加载项 - 如何读取自定义文档属性

提问于
浏览
3

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

目前,我可以通过执行以下操作向Word文档添加自定义属性:

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

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

但我无法阅读该 properties .

我想这样做:

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"

哪个是阅读房产的正确方法?

(我正在使用这个办公室js: appsforoffice.microsoft.com/lib/beta/hosted/office.js

2 回答

  • 3

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

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

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

    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);
                 })
         })
    }
    
  • 0

    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);
              });
          });
      });
    }
    

相关问题