我有一个使用 Office/Excel Javascript API 用 React 编写的 Excel 插件。我面临以下挑战:
如何在 Excel 文档中启动并保持 onSelectionChanged 事件活动?
请参阅下面的我的 index.js 代码。
import 'office-ui-fabric-react/dist/css/fabric.min.css';
import App from './components/App';
import { AppContainer } from 'react-hot-loader';
import { initializeIcons } from 'office-ui-fabric-react/lib/Icons';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
initializeIcons();
let isOfficeInitialized = false;
const title = 'Excel Plugin';
const render = (Component) => {
ReactDOM.render(
<AppContainer>
<Router>
<div>
<Route
path="/:token"
component={({ match, location }) => {
return <Component title={title} isOfficeInitialized={isOfficeInitialized} match={match} location={location} />;
}}
/>
</div>
</Router>
</AppContainer>,
document.getElementById('container')
);
};
/* Render application after Office initializes */
Office.initialize = () => {
//Create global click event
Excel.run(async function (context) {
context.workbook.onSelectionChanged.add(handleChange);
return context.sync();
}).catch(errorHandlerFunction);
function handleChange(e) {
console.log('Clicking cell!');
Excel.run(async function (context) {
let range = context.workbook.getSelectedRange();
range.values = 'Clicked!';
return context.sync();
});
}
function errorHandlerFunction(e) {
console.log(e);
}
render(App);
};
Office.onReady = () => {
Office.addin.setStartupBehavior(Office.StartupBehavior.load);
};
/* Initial render showing a progress bar */
render(App);
if (module.hot) {
module.hot.accept('./components/App', () => {
const NextApp = require('./components/App').default;
render(NextApp);
});
}
默认情况下,您的加载项将在单独的 JavaScript 运行时环境中运行功能区按钮、自定义函数和任务窗格的代码。这会产生一些限制,例如无法轻松共享全局数据,以及无法从自定义函数访问所有 CORS 功能。
但是,您可以将 Excel 加载项配置为在同一 JavaScript 运行时(也称为共享运行时)中共享代码。这样可以更好地协调整个加载项,并从加载项的所有部分访问任务窗格 DOM 和 CORS。
通过共享运行时,您的加载项可以在任务窗格关闭后继续运行代码。
本文解释如何配置共享运行时
为了回答你的第四点,“当任务窗格关闭时,事件再次停止工作”,我做了一个解决办法,将我的配置转换为共享运行时。为了即使在用户关闭任务窗格时也能继续运行该功能,我在 manifest.xml 文件中添加了一些配置,如下所示: