首页 > 解决方案 > 如何获取当前打开的excel工作簿的本地路径?

问题描述

我在 Visual Studio 2017 中使用默认的“Excel Web 加载项”模板。我正在尝试创建一个 Excel 加载项,将现有工作簿的副本插入到当前工作簿中。第一步是获取当前工作簿的完整路径和名称。我从这里得到了代码。我正在使用 beta excel API。在'var myFile = document.getElementById("file");'这一行 myFile 始终为空。我认为空值是因为工作簿没有“加载”,但是当我运行程序时工作簿确实打开了。

这是来自 Home.js 的代码:

'use strict';

(function () {
    Office.onReady(function () {
        // Office is ready
        $(document).ready(function () {
            // The document is ready
            $('#RunMacroButton').click(RunMacro);
        });
    });

    function RunMacro() {


        var myFile = document.getElementById("file");
        var reader = new FileReader();

        reader.onload = (function (event) {
            Excel.run(function (context) {
                // strip off the metadata before the base64-encoded string
                var startIndex = event.target.result.indexOf("base64,");
                var workbookContents = event.target.result.substr(startIndex + 7);

                Excel.createWorkbook(workbookContents);
                return context.sync();
            }).catch(errorHandlerFunction);
        });

        // read in the file as a data URL so we can parse the base64-encoded string
        reader.readAsDataURL(myFile.files[0]);

    }
})();

标签: javascriptexcel-addins

解决方案


'var myFile = document.getElementById("file");' 行 始终为 null,因为没有称为“文件”的元素。这也是获取当前打开的工作簿路径的错误方式。而是使用“Office.context.document.url”返回路径。


推荐阅读