Excel JS React-运行代码而不打开Taskpane

问题描述

我有一个使用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。

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

本文介绍了如何configure shared runtime

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...