我正在使用“用于Office插件的JavaScript API”在我的HTML程序中创建excel文件。
但是,当我加载页面时,这会返回一条错误消息。
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/Office.js" type="text/javascript"></script>
<script>
Excel.run(function (context) {
console.log('Your code goes here.');
}).catch(function (error) {
console.log('error: ' + error);
});
</script>
<head>
这将返回错误消息“Uncaught ReferenceError:Excel未定义”。
Sivcan的评论是正确的。当加载项加载时,API功能不能立即可用(并且通常甚至不在JS变量中定义),您需要等到调用Office.onReady
(或其旧的等价物,Office.initialize
)。
在你的情况下,这应该工作:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js></script>
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/Office.js" type="text/javascript"></script>
<script>
Office.onReady(() => {
Excel.run(function (context) {
console.log('Your code goes here.');
}).catch(function (error) {
console.log('error: ' + error);
});
});
</script>
</head>
<body>
</body>