需要帮助将 .docx 文件加载到当前文档中

Need help loading a .docx file into current document

我正在编写一个加载项,用户可以在其中选择加载不同的预定义模板。

我的电脑上有这些模板作为 docx 文件。

我知道方法 body.insertFileAsBase64,但我无法使用它!

function insertTemplate01() {
    Word.run(function (context) {

        var body = context.document.body;
        body.clear();
        body.insertText("rapport 1", "Start");


        return context.sync();

    });
}

所以我不想只插入一个字符串,而是想加载一个 .docx 文件作为模板。

我想我需要有关如何执行此操作的入门指南。

我不知道如何将我的 docx 文件转换为 base64,然后使用它们加载到当前文档中。

非常感谢!

body.insertFileAsBase64 必须适合您的目的。 我假设您遇到 docx 文件的 base64 编码问题。查看此 "silly stories" 示例,展示如何获取 base64,然后将其插入文档,假设文档在某些 URL.

中可用

https://github.com/OfficeDev/Word-Add-in-SillyStories/blob/master/sample.js

这是关于如何从二进制文件中获取 base64 的另一个讨论: Convert binary data to base64 with javascript

要将二进制流转换为 base64,您可以这样做:

  function insertPickedFile() {
        var myFile = document.getElementById("FileToPick"); // assuming there is a <input type="file" id="FileToPick"> element, btw this will be the handler for its change event.. so  you also need to initialize a handler like      $('#FileToPick').change(insertPickedFile);
    
        var reader = new FileReader();
        reader.onload = (function (theFile) {
            return function (e) {
               
                Word.run(function (context) {
                    var startIndex = e.target.result.indexOf("base64,"); // when you use the readAsDataURL method the base64 is included in the result, we just need to get that substring, and then insert it using office.js :)
                    var mybase64 = e.target.result.substr(startIndex + 7, e.target.result.length);
                    context.document.body.insertFileFromBase64(mybase64, "replace");
                    return context.sync()       

                })                               
            };
        })(myFile.files[0]);

        // Read in the image file as a data URL.
        reader.readAsDataURL(myFile.files[0]);
    
}