既然选择了 electron, 如果可以直接调用 com 组件那就再好不过了, 搜索一番后发现有一款软件可以实现 node 直接创建 com 组件, 那就是 winax
1. 安装
npm i winax
一般情况下是安装不成功的, 需要准备前置条件
2. 编译环境
This project uses Visual C++ 2013 (or later versions then support C++11 standard). Bulding also requires node-gyp and python 2.6 (or later) to be installed. Supported NodeJS Versions (x86 or x64): 10, 11, 12, 13, 14, 15 You can do this with npm:
安装 windows-build-tools(需要以管理员身份运行终端再进行安装)
npm install --global --production windows-build-tools
上一步由于是从国外地址下载,大概率下载不了会出现 依赖安装失败的错误,会在终端显示 “Could not install Visual Studio Build Tools.”的字样
解决办法如下:
1>进入到 c盘/用户(users)/(你当前用户名)/.windows-build-tools/vs_BuildTools.exe 出现弹窗就点击继续或者修改
2>已安装目录下 Visual Studio 15 生成工具2017 点击右侧的修改
3>Windows大标题下的 Visual C++ 生成工具 以及 未分类大标题下得到 Node.js生成工具,在点击右侧的修改安装依赖 (安装时间可能有点长,请耐心等待)
4>然后再继续下面的流程
还有部分会出现一直卡在安装页面,解决方案请自行百度
3. 安装问题
安装过程中会出现很多奇奇怪怪的问题, 下面是我遇到的一些坑
3.1 提示 vs 版本错误
可以指定 --msvs_version=2017 然后再重新执行安装
npm config set --msvs_version=2017 --global
或者安装时就指定 vs 版本
npm install winax --msvs_version=2017
3.2 编译版本问题
Error: The module '\?\F:\invoice\github\electron-vue-edge\node_modules\winax\build\Release\node_activex.node'\
was compiled against a different Node.js version using\
NODE_MODULE_VERSION 83. This version of Node.js requires\
NODE_MODULE_VERSION 89. Please try re-compiling or re-installing\
the module (for instance, using `npm rebuild` or `npm install`).
使用时如果出现这个问题, 需要执行
npm rebuild winax --runtime=electron --target=13.0.0 --dist-url=https://electronjs.org/headers --build-from-source
如果上述操作不能解决问题需要使用 electron-rebuild 进行编译
npm install --save-dev electron-rebuild
./node_modules/.bin/electron-rebuild
如果执行过程中报错,请查看报错并对应解决即可
或者更换 node 版本,我当前版本信息是:
"winax": "^3.3.4"
"node": "14.18.0"
3.3 32 vs 64 Bit
winax 使用的是和你当前 node 相同的版本, 如果需要安装 32 位就需要 node 也安装 32 位的, 那么可以直接去node 官网下载对应 32 的 node 程序, 也可以使用 node 版本管理工具 nvm
4 使用
winax 使用比较简单
const ExcelSheet = new winax.Object('Excel.Sheet')
ExcelSheet.Application.Visible = true;
ExcelSheet.ActiveSheet.Cells(1,1).Value = "This is column A, row 1";
ExcelSheet.SaveAs('D:\TEST.XLS')
ExcelSheet.Application.Quit()