reactjs - Excel JS React - 在不打开任务窗格的情况下运行代码
问题描述
我有一个使用 Office/Excel Javascript API 用 React 编写的 Excel 插件。我面临以下挑战:
- 我正在尝试创建一个全局单击事件来检测单元格单击并查找绑定
- 如果绑定可用,则应打开特定的任务窗格
- 问题是 onSelectionChanged 事件处理程序仅在任务窗格打开时才有效。
- 当任务窗格关闭时,事件将不再工作
- manifest.xml 文件配置有打开任务窗格的“ShowTaskpane”操作。
如何在 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。
使用共享运行时,您的加载项可以在任务窗格关闭后继续运行代码。
本文讲解如何配置共享运行时
推荐阅读
- javascript - 如何:使用 React Native 为 9gag 的“添加按钮”设置动画
- python - Python - 使用子进程在目录和子目录中查找包含特定文本的所有文件
- c# - 值类型的“is T x”的实现和性能
- c# - 获取属性 c# 的返回与分配
- python - 谷歌分析 API:使用正则表达式的 IN 列表
- c++ - 在 LINUX 中构建 Gtest 框架
- c# - CaliburnMicro 中的 IsVisible 未链接
- c# - 获取 .NET Core JsonSerializer 以序列化私有成员
- reactjs - ownProps 是否默认传递给组件?
- c++ - 如何创建具有不同签名的容器存储功能?