【问题标题】:How to store values(key, value) pair in a word document如何在word文档中存储值(键,值)对
【发布时间】:2017-03-06 11:47:51
【问题描述】:

我正在使用 word JavaScript API 开发一个 word 插件。我需要在文档的上下文中存储一些值,因此当我在同一客户端或其他客户端上再次打开文档时,想要从文档中获取该值并执行一些操作。我已经尝试使用设置对象,但设置对象是按加载项和每个文档保存的,因此值在其他客户端加载项上不可用。请指导我如何存储随文档随处可用的值。

谢谢。

【问题讨论】:

    标签: ms-word office365 office-js word-addins javascript-api-for-office


    【解决方案1】:

    【讨论】:

    【解决方案2】:

    您还可以存储包含所有您需要的数据的 XML 部分,基本上是存储在文档中的 XML 文件。查看此示例,了解如何添加和检索 xml 部件。 https://github.com/OfficeDev/Word-Add-in-Work-with-custom-XML-parts/blob/master/C%23/CustomXMLAppWeb/App/Home/Home.js

    顺便说一句,我建议您使用文档属性,它似乎更适合您的需求。确保您使用 Word 中的最新更新!

    这是一个关于如何创建文档属性的示例(第一个示例是数值,第二个示例是字符串):

    function insertNumericProperty() { 
            Word.run(function (context) {
                context.document.properties.customProperties.add("Numeric Property", 1234);
                return context.sync()
                    .then(function () {
                        console.log("Property added");     
                    })
                    .catch(function (e) { 
                        console.log(e.message);
                    })
            })
    
        }
    
        function insertStringProperty() { 
            Word.run(function (context) {
                context.document.properties.customProperties.add("String Property", "Hello World!");
                return context.sync()
                    .then(function () {
                        console.log("Property added");     
                    })
                    .catch(function (e) { 
                        console.log(e.message);
                    })
            })
        }

    这里是如何检索它们的代码:

    function readCustomDocumentProperties() { 
            Word.run(function (context) {
                var properties = context.document.properties.customProperties;
                context.load(properties);
                return context.sync()
                    .then(function () {
                        for (var i = 0; i < properties.items.length; i++)
                            console.log("Property Name:" + properties.items[i].key + ";Type=" + properties.items[i].type +"; Property Value=" + properties.items[i].value);
                    })
                    .catch(function (e) { 
                        console.log(e.message);
                    })
            })
        }

    【讨论】:

    • 感谢您的建议,我已按照上面的链接进行操作,但无法在文档中添加、编辑和删除键/值对。您能否提供一些对我有很大帮助的工作代码。谢谢。
    • 上面的代码是功能性的,它的想法是你保存一个包含所有你需要的名称/值对的 XML 文档。在这一点上,我建议您尝试自定义文档属性,这似乎是您想要做的更好的解决方案。
    • 我添加了有关如何创建和读取自定义文档属性的更多详细信息。谢谢
    • 非常感谢您对示例代码的回复,它运行良好:) 我可以在哪里找到有关“customProperties”的更多信息。
    • 在 Philip 在第一个答案中分享的链接中!如果您还有其他问题,请告诉我。
    猜你喜欢
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-14
    相关资源
    最近更新 更多