Office.js 函数在 Word Online 的 MVC 应用程序中不起作用

Office.js function not working in MVC application for Word Online

我有一个 Word 在线 .NET MVC 项目。加载项成功启动,但未加载 "Home.js",它调用 Office.initialize 将数据插入到 word 正文中。

这里是_Layout.cshtml:

<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    @Styles.Render("~/bundles/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body ng-app="">
    <div class="container">
        @RenderBody()
    </div>
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/Scripts/Office/1/office.js")
    @Scripts.Render("~/Scripts/Home.js")
    @Scripts.Render("~/bundles/bootstrap")
    @Scripts.Render("~/Scripts/angular.min.js")
</body>
</html>

和Home.js:

(function () {
    "use strict";

    Office.initialize = function (reason) {
        $(document).ready(function () {
            if (!Office.context.requirements.isSetSupported('WordApi', '1.1')) {
                return;
            }
            loadSampleData();
        });
    };

    function loadSampleData() {

        // Run a batch operation against the Word object model.
        Word.run(function (context) {
            // Create a proxy object for the document body.
            var body = context.document.body;
            // Queue a commmand to clear the contents of the body.
            body.clear();
            // Queue a command to insert text into the end of the Word document body.
            body.insertText("This is a sample text inserted in the document",
                            Word.InsertLocation.end);

            // Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
            return context.sync();
        })
        .catch(errorHandler);
    }

    function errorHandler(error) {
        console.log("Error: " + error);
        if (error instanceof OfficeExtension.Error) {
            console.log("Debug info: " + JSON.stringify(error.debugInfo));
        }
    }
})();

谢谢。

您仅在 WordAPI v1.1 可用时执行。此 API 仅在 Word 2016 for Windows, Mac and iPad 中受支持。如果您使用的是 Word Online 或 Word 2013,此代码将退出 (return) 而不执行任何操作。

另一个注意事项,您在 <body> 的底部引用了 Office.js 和 Home.js。您只有 5 秒的时间来完成 Office.initialize() 并将其放在页面底部将需要在浏览器执行该功能之前加载所有内容。虽然这对网站来说绝对是正确的做法,但它会导致加载项出现超时错误。这些引用 should always be placed within the <header>