Excel JS React - 无需打开任务窗格即可运行代码

问题描述 投票:0回答:2

我有一个使用 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);
    });
}
reactjs office-js
2个回答
0
投票

默认情况下,您的加载项将在单独的 JavaScript 运行时环境中运行功能区按钮、自定义函数和任务窗格的代码。这会产生一些限制,例如无法轻松共享全局数据,以及无法从自定义函数访问所有 CORS 功能。

但是,您可以将 Excel 加载项配置为在同一 JavaScript 运行时(也称为共享运行时)中共享代码。这样可以更好地协调整个加载项,并从加载项的所有部分访问任务窗格 DOM 和 CORS。

通过共享运行时,您的加载项可以在任务窗格关闭后继续运行代码。

本文解释如何配置共享运行时


0
投票

为了回答你的第四点,“当任务窗格关闭时,事件再次停止工作”,我做了一个解决办法,将我的配置转换为共享运行时。为了即使在用户关闭任务窗格时也能继续运行该功能,我在 manifest.xml 文件中添加了一些配置,如下所示:

运行加载项而不显示任务窗格?

© www.soinside.com 2019 - 2024. All rights reserved.