大家好,我在尝试用pyinstaller打包excel文件时,遇到如下问题:
步骤1:通过如下代码调用excel文件。
......
import xlwings as xw
app = xw.App(visible=True, add_book=False)
wb = app.books.open('.\\ecs\\als.xlsx')
......
步骤2:通过修改spec文件设置,将ecs文件夹中的文件(包括als.xlsx),打包到生成的exe中的ecs文件夹下。
......
a = Analysis(
['entr.py'],
pathex=['C:\\Users\\Administrator\\PycharmProjects\\pythonProject3\\Package_20230131'],
binaries=[],
datas=[('.\\ecs','.\\ecs'),
......
但是实际执行时发现,无法打开ecs文件夹下面的als.xlsx文件,且exe程序会因无响应而退出。
但是如果直接把含有als.xlsx的ecs文件夹,放在exe同目录下,是可以读取到的。
通过网络搜索未发现类似问题的解答,请问大家是否遇到过类似问题。
该如何设置,才能实现将excel文件通过pyinstaller打包到exe中,并通过xlwings调用?
非常感谢!
您需要通过修改spec文件,将ecs文件夹中的als.xlsx文件正确地打包到exe程序中,以便程序可以在运行时正确读取它。同时,您还需要确保在运行时将打包后的ecs文件夹中的文件路径传递给xlwings。
以下是一些可能有用的步骤:
在spec文件中添加Tree元组来指定ecs文件夹中包含的文件应该打包到哪个目录下。例如:
a = Analysis(['entr.py'],
pathex=['C:\\Users\\Administrator\\PycharmProjects\\pythonProject3\\Package_20230131'],
binaries=[],
datas=[],
# Add this Tree element to include the ecs folder and its contents in the build
trees=[Tree('.\\ecs')],
hiddenimports=['xlwings._xlwindows'])
在代码中使用sys._MEIPASS获取打包后的exe程序的路径,以便正确读取打包后的文件。例如:
import sys
import xlwings as xw
if hasattr(sys, '_MEIPASS'):
# This code will run if the script is run from a PyInstaller executable
app = xw.App(visible=True, add_book=False)
# Use os.path.join to safely join the path to the executable with the name of the file
wb = app.books.open(os.path.join(sys._MEIPASS, 'ecs', 'als.xlsx'))
else:
app = xw.App(visible=True, add_book=False)
wb = app.books.open('.\\ecs\\als.xlsx')
在此示例中,我们使用os.path.join函数来组合路径,以确保路径正确。sys._MEIPASS变量包含了PyInstaller打包后的程序所在的路径。
希望这些步骤能帮助您正确地使用PyInstaller打包Excel文件,并通过xlwings调用它。
你必须打包成文件夹,打包一个exe里面怎么可能会有文件夹呢
你把py文件打包成文件夹之后,如果有必要,可以再用另一种打包工具把文件夹打包成安装包