【问题标题】:Including excel files with program in Pyinstaller在 Pyinstaller 中包含带有程序的 excel 文件
【发布时间】:2020-04-15 19:14:21
【问题描述】:

我在 python 中编写了打开一个模板 excel 文件的代码。每天午夜,它都会将该模板复制到一个新的 Excel 文件中,代码将在其中记录当天的数据。我的目标是使用 pyinstaller 创建一个包含我的代码和模板 excel 文件的单个可执行文件。

基本上我希望能够通过将excel文件捆绑到从pyinstaller获得的exe文件中来打开模板excel文件,无论计算机是否包含该文件:

现在我打开excel文件如下图:

import os
import openpyxl

theFile = openpyxl.load_workbook(os.getcwd()+"\templateExcel.xlsx")
currentSheet = theFile[theFile.sheetnames[0]]

但是,当我将 excel 文件作为 --add-data "templateExcel.xlsx;templateExcel.xlsx 包含到 pyinstaller 命令中并运行 exe 文件时,它无法检测到 templateExcel 文件的位置。我知道通过在另一台计算机上运行,​​ os.getcwd() 给出了不同的路径,因此它显然无法打开 excel 文件。因此,我需要一种将 excel 文件捆绑到 exe 文件中的方法,以便无论计算机如何,python 代码都可以找到它。

【问题讨论】:

    标签: python excel pyinstaller


    【解决方案1】:

    你可以使用; Adding a data file in Pyinstaller using the onefile option
    总结:

    pyinstaller --onefile --nowindow --add-data text.txt;included winprint.py --distpath .
    

    和示例 python 脚本:

    import os 
    import sys
    
    os.chdir(sys._MEIPASS)
    os.system('included\\text.txt')
    

    【讨论】:

    • 您不需要 chdir,您可以将相对路径 ('included\\text.txt') 附加到 sys._MEIPASS。此外,你不应该这样做,除非你确定那是你想要的。
    【解决方案2】:

    请注意: 使用“getcwd()”时,您不会收到您想要的结果,它会为您提供执行 exe 文件的位置。

    例如,看下面的长模块:

    from os import getcwd
    print(getcwd())
    

    如果你从不同的位置执行它,你会得到不同的结果:

    如果 PyInstaller 像您认为的那样工作(将文件相对于某个模块放置),您可以使用 file 而不是 getcwd() 因为它指示模块所在的位置(这是恒定的,不像exe 执行的位置),但它没有。

    无论如何,@Sezer BOZKIR 的回答就足够了,请注意我在那里添加的评论。

    【讨论】:

      猜你喜欢
      • 2020-11-08
      • 2018-10-05
      • 1970-01-01
      • 1970-01-01
      • 2020-08-15
      • 2016-08-01
      • 2020-11-17
      • 1970-01-01
      • 2018-01-02
      相关资源
      最近更新 更多