You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在现有VSTO项目中集成Office JS?

在VSTO加载项中集成Office JS实现报表弹窗功能

核心思路

在现有VSTO加载项中,通过弹窗嵌入WebBrowser控件加载基于Office JS的报表页面,既可以复用现有Web平台的报表代码,又能借助Office JS直接与Office应用交互,实现报表数据的动态获取和展示。

步骤1:编写基于Office JS的报表Web页面

准备可复用的Web报表页面,集成现有Web平台的报表逻辑,同时通过Office JS对接Office应用数据:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Office报表</title>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <!-- 引入Office JS库 -->
    <script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js"></script>
    <script>
        // 初始化Office JS
        Office.initialize = function(reason) {
            // 调用现有Web平台的报表初始化逻辑
            initReport();
        };

        // 复用现有Web平台的报表初始化函数
        function initReport() {
            // 示例:通过Office JS获取Excel当前选中区域数据
            Excel.run(async (context) => {
                const range = context.workbook.getSelectedRange();
                range.load('values');
                await context.sync();
                
                // 将数据传入现有报表渲染逻辑
                renderReport(range.values);
            }).catch(error => {
                console.error(error);
            });
        }

        // 复用现有Web平台的报表渲染函数
        function renderReport(data) {
            const reportContainer = document.getElementById('report-container');
            // 这里直接替换成你现有Web平台的报表渲染代码
            reportContainer.innerHTML = `<h3>当前选中区域报表</h3><pre>${JSON.stringify(data, null, 2)}</pre>`;
        }
    </script>
</head>
<body>
    <div id="report-container"></div>
</body>
</html>

步骤2:在VSTO中创建Web弹窗

在VSTO项目中添加Windows窗体作为弹窗,嵌入WebBrowser控件加载上述报表页面:

  1. 右键VSTO项目 → 添加 → Windows窗体(命名为ReportPopup)
  2. 在窗体中添加WebBrowser控件(命名为webBrowser1),设置控件Dock属性为Fill
  3. 在VSTO功能区按钮的点击事件中,弹出窗体并加载报表页面:
private void btnShowReport_Click(object sender, RibbonControlEventArgs e)
{
    // 加载本地报表页面(也可以替换为内网部署的Web地址)
    string reportUrl = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Report.html");
    
    var popup = new ReportPopup();
    popup.webBrowser1.Navigate(reportUrl);
    popup.ShowDialog();
}

步骤3:配置WebBrowser控件兼容Office JS

默认WebBrowser控件使用IE7模式,需配置为IE11以兼容Office JS:
在项目根目录添加app.manifest文件,加入以下配置:

<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
    <application>
        <!-- 声明兼容IE11 -->
        <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
    </application>
</compatibility>

双向通信扩展(可选)

若需要VSTO与Web页面交互:

  • VSTO调用Web页面JS函数:webBrowser1.InvokeScript("renderReport", new object[] { dataFromVSTO });
  • Web页面调用VSTO公开方法:在VSTO窗体类中添加[ComVisible(true)]属性,Web页面通过window.external.VSTOMethodName()调用

内容的提问来源于stack exchange,提问作者Alex L

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 05:28:29