如何使用Word插件/加载项在Word文档中插入文本

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

我使用 yeoman 开发了一个单词插件/插件。现在我陷入了困境,我从 Word 加载项调用 Rest API,并且我从 Rest API 调用中获取字典中键值对形式的内容,并且需要将该文本插入到 Word 文档中与响应中的键相同的标题下。

可行吗?或者我们可以从API获取word文档,然后我们可以使用word插件/插件在同一窗口/word屏幕上显示这个api对象(word文档)?

ms-word office-js office-addins word-addins word-web-addins
2个回答
0
投票

您可以获取base64文件,然后使用以下代码:

function onaddOpenDoc() {
        Word.run(function (context) {
          
          // this getDocumentAsBase64 assumes a valid base64-encoded docx file
            var myNewDoc = context.application.createDocument(getDocumentAsBase64());
            context.load(myNewDoc);

            return context.sync()
                .then(function () {
                    myNewDoc.open();
                    context.sync();
                }).catch(function (myError) {
                    //otherwise we handle the exception here!
                    showNotification("Error", myError.message);
                })

        }).catch(function (myError) { showNotification("Error", myError.message); });


    }

0
投票

您可以尝试以下解决方案

Word.run(async (context: any) => {
  const docBody = context.document.body;
  context.load(docBody, "text");
  await context.sync();

  const newDoc = context.application.createDocument();
  context.load(newDoc);

  return context.sync().then(async () => {
    newDoc.body.insertText(docBody.text, Word.InsertLocation.start);
    await context.sync();

    const paragraphs = newDoc.body.paragraphs;
    context.load(paragraphs, "items");
    await context.sync();

    for (let i = 0; i < paragraphs.items.length; i++) {
      const para = paragraphs.items[i].text.trim();

      if (para != "APIkey") {
        // <------ check with your KEY
        const para = paragraphs.items[i]
          .getRange()
          .insertText("APIsKeyResponse", Word.InsertLocation.replace); // <------ replace with your value
        await context.sync();
      }
    }
    newDoc.open();
    return context.sync();
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.