如何使用 office.js api 更新文档字段

问题描述 投票:0回答:1

如果存在,我想用新值更新文档的所有自定义属性字段。我在这里使用 insertText() 函数,但它似乎不适用于字段。我需要一些函数来使用给定的(文档自定义属性)值更新字段值。这是我的代码。

Word.run(function (context) {
    var customDocProps = context.document.properties.customProperties;
    // first, load custom properties object
    context.load(customDocProps);
    return context.sync()
        .then(function () {
            // now load actual property
            var filenameProp = customDocProps.getItemOrNullObject("PW", { matchPrefix: true });
            context.load(filenameProp);
            return context.sync()
                .then(function () {
                    if (customDocProps.items.length > 0) {
                        var fields = context.document.body.fields.load("items");
                        fields.load(["code", "result"]);
                        return context.sync()
                            .then(function () {
                                if (fields.items.length > 0) {
                                    $.each(fields.items, function (i, k) {
                                        $.each(customDocProps.items, function (j, l) {
                                            if (k.code.trim().replace(/\s\s+/g, ' ').split(' ')[1].toLowerCase() == l.key.toLowerCase()) {
                                                //replace if values are different
                                                if (k.result.text != l.value) {                                                
                                                    k.result.insertText(k.result.text, l.value);
                                                    k.load(["code", "result"]);
                                                    return context.sync();
                                                }
                                                else {
                                                    return false;
                                                }
                                            }
                                        });
                                    });
                                }
                            });
                    }
                });
        });
}).catch(function (error) {
    debugger;
    console.log('Error: ' + JSON.stringify(error));
    if (error instanceof OfficeExtension.Error) {
        console.log('Debug info: ' + JSON.stringify(error.debugInfo));
    }
});
office-js
1个回答
0
投票

字段可以这样更新: k.result.insertText(k.result.text, loc); 位置可以是“开始”“结束”“之前”“之后”“替换”的字符串。

我注意到customProperties.getItemOrNullObject只有一个输入参数。请您参考这个链接:在此处输入链接描述并检查是否存在语法错误。

在我将 getItemOrNullObject 修改为仅一个参数后,我在您的代码中放置了多个 console.log("flag") 并强制 if 条件始终为真。整个代码可以执行成功,日志也可以输出到控制台。我认为您可以检查 if 条件并尝试记录以查看每个变量值是否正确。

© www.soinside.com 2019 - 2024. All rights reserved.