如何使用openpyxl与cx_Freeze一起使用。

问题描述 投票:1回答:1

我使用openpyxl来修改现有的excel,并将其与我的结果一起保存。它在temrinal上运行良好。

我尝试用cx_freeze把我的项目放在.exe上。一切都正常,除了用openpyxl的部分。

我想这是由我使用的 "路径 "引起的。

current_path = str(os.path.dirname(os.path.realpath(__file__)))
file_path =  current_path + r"\folder\filename.xlsx"
wb = openpyxl.load_workbook(file_path)

我怎样才能打开我的excel文件,它将被存储在.exe旁边的文件夹中,或者将它们包含在setup.py中? 我有几个模型。

提前感谢您的帮助。

python-3.x excel openpyxl cx-freeze os.path
1个回答
0
投票

嗯...我在cx_Freeze文档中找到了它,抱歉! 如果有帮助的话,我就把答案贴出来,给像我这样的初学者加点注释:

import sys
def find_data_file(filename):
   if getattr(sys, 'frozen', False):
       # The application is frozen: no need to change anything
       datadir = os.path.dirname(sys.executable)
   else:
       # The application is not frozen: if you run it on terminal
       # Change this bit to match where you store your data files:
       datadir = os.path.dirname(__file__) #__file__ could be replace for example: os.path.realpath(__file__)
return os.path.join(datadir, filename)

在文件名中, 不要忘了包含 \\: "\aFolder\myFile.xlsx"

在替换我上面的代码(没有函数)时,它对我来说很好用。

if getattr(sys, 'frozen', False):
    current_path = str(os.path.dirname(sys.executable))
else:
    current_path = str(os.path.dirname(os.path.realpath(__file__)))

file_path =  current_path + r"\folder\filename.xlsx"
wb = openpyxl.load_workbook(file_path)
© www.soinside.com 2019 - 2024. All rights reserved.