1

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

谢谢。

回答

1

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

btw我会推荐你​​使用文档属性,它似乎更适合你的需求。确保您使用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); 
 
       }) 
 
     }) 
 
    }

+0

感谢您的建议,我已经按照上面的链接,但无法添加,编辑和删除文档中的键/值对。你能否给我提供一些能帮助我很多的工作代码。谢谢。 – Amit

+0

上面的代码是功能性的,这个想法是,你保存一个XML文档,包含你需要的所有名称/值对。在这一点上,我会建议你尝试自定义文件属性,它似乎是一个更好的解决方案,你想要做什么。 –

+0

我添加了更多关于如何创建和读取自定义文档属性的细节。谢谢 –

相关问题