Office.js函数无法在Word Online的MVC应用程序中运行

时间:2016-06-28 13:52:48

标签: asp.net-mvc ms-office office365-apps office-js

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

这是_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));
        }
    }
})();

谢谢。

1 个答案:

答案 0 :(得分:0)

只有在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>