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

如何在Excel内容加载项中导入并使用Puppeteer?

问题分析与解决方案

首先明确:Puppeteer是Node.js专属库,无法直接在Excel加载项的前端浏览器环境中运行——它依赖Node.js的进程管理能力来启动本地浏览器,而前端浏览器没有访问本地系统进程的权限,也不支持require这类Node.js模块导入语法。你的代码同时存在语法错误,但核心问题是运行环境不匹配。

正确实现思路

把Puppeteer的逻辑放到Node.js后端服务中,前端Excel加载项通过HTTP请求调用后端接口,由后端完成浏览器启动和后续操作。

步骤1:搭建Node.js后端服务

创建一个简单的Express服务,封装Puppeteer的逻辑:

const express = require('express');
const puppeteer = require('puppeteer');
const cors = require('cors');
const app = express();
const port = 3000;

app.use(cors());
app.use(express.json());

// 定义接口,处理前端的浏览器启动请求
app.post('/launch-browser', async (req, res) => {
  try {
    const browser = await puppeteer.launch();
    // 这里可添加Puppeteer操作,比如打开页面、截图等
    res.json({ success: true, message: '浏览器已启动' });
    // 记得在操作完成后关闭浏览器,避免资源泄漏
    // await browser.close();
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

app.listen(port, () => {
  console.log(`后端服务运行在 http://localhost:${port}`);
});

步骤2:修改Excel加载项前端代码

去掉前端的require和Puppeteer调用,改为向后端发送请求:

(function () {
    "use strict";

    Office.initialize = function (reason) {
        $(document).ready(function () {
            $("#compare").click(async function () {
                try {
                    const response = await fetch('http://localhost:3000/launch-browser', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });
                    const result = await response.json();
                    if (result.success) {
                        console.log(result.message);
                        // 处理成功后的业务逻辑
                    } else {
                        console.error('启动失败:', result.error);
                    }
                } catch (error) {
                    console.error('请求后端失败:', error);
                }
            });
        });
    };
})();

步骤3:关键注意事项

  • 启动后端前,先安装依赖:npm install express puppeteer cors
  • 后端服务需和Excel加载项在同一网络环境下,确保前端能访问到后端地址
  • Puppeteer运行需要对应系统的浏览器环境,它会自动下载Chromium,也可手动指定本地浏览器路径

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 22:36:28