使用Jpype+AsposeCells打包EXE失败:无法导入com.aspose
问题:PyInstaller打包Jpype+AsposeCells代码后报ClassNotFoundException: com.aspose
问题详情
基于Anaconda做SAP自动化开发,用Jpype调用AsposeCells实现Excel只读密码保护,代码如下(已补全缺失的datetime导入):
import jpype import asposecells from datetime import datetime jpype.startJVM() from asposecells.api import Workbook timestamp = datetime.now().strftime("%Y%m%d%H%M") workbook = Workbook("G:\\t.xlsx") workbook.getSettings().getWriteProtection().setPassword("1234") workbook.getSettings().getWriteProtection().setAuthor("asd") workbook.save("G:/p_out " + timestamp + ".xlsx") jpype.shutdownJVM()
用PyInstaller打包成EXE后运行,抛出如下错误:
Traceback (most recent call last): File "org.jpype.JPypeContext.java", line -1, in org.jpype.JPypeContext.callMethod Exception: Java Exception The above exception was the direct cause of the following exception: Traceback (most recent call last): File "jpype\imports.py", line 195, in find_spec java.lang.java.lang.ClassNotFoundException: java.lang.ClassNotFoundException: com.aspose The above exception was the direct cause of the following exception: Traceback (most recent call last): File "example.py", line 270, in <module> File "PyInstaller\loader\pyimod02_importers.py", line 385, in exec_module File "asposecells\api.py", line 10, in <module> File "jpype\imports.py", line 203, in find_spec ImportError: Failed to import 'com.aspose' [18204] Failed to execute script 'example' due to unhandled exception!
已将AsposeCells的.jar文件放入项目目录并修改了.spec文件,但问题依旧。
解决步骤
1. 修正.spec文件的资源配置
打开生成的.spec文件,找到datas字段,添加Jar文件的复制规则,确保打包时Jar文件被复制到EXE同级目录:
# 假设asposecells.jar在项目根目录,修改后datas如下 datas=[('asposecells.jar', '.'),]
2. 代码中手动指定Jar加载路径
打包后程序无法自动识别Jar位置,需要在启动JVM时明确指定classpath:
import os import jpype import asposecells from datetime import datetime # 获取当前程序运行目录(打包后为EXE所在目录) current_dir = os.path.dirname(os.path.abspath(__file__)) # 拼接Jar文件的绝对路径 jar_path = os.path.join(current_dir, "asposecells.jar") # 启动JVM时加载指定Jar jpype.startJVM(classpath=[jar_path]) from asposecells.api import Workbook # 后续业务代码不变 timestamp = datetime.now().strftime("%Y%m%d%H%M") workbook = Workbook("G:\\t.xlsx") workbook.getSettings().getWriteProtection().setPassword("1234") workbook.getSettings().getWriteProtection().setAuthor("asd") workbook.save("G:/p_out " + timestamp + ".xlsx") jpype.shutdownJVM()
3. 重新打包
使用修改后的.spec文件执行打包:
pyinstaller your_script_name.spec
4. 版本兼容性检查
- 确认AsposeCells Jar版本与Python的asposecells库版本一致
- 确保Jpype依赖的JVM(本地安装的Java环境)与Jar文件的位数匹配(均为64位或32位)
内容的提问来源于stack exchange,提问作者macikeci
相关产品推荐
相关产品推荐

