Search code examples
python-3.xexcelopenpyxlcx-freezeos.path

How to use openpyxl with cx_Freeze


I use openpyxl to modify an existing excel and saving it with my results. It works well on the temrinal.

I try to have my project on .exe with cx_freeze. Everything works expect the part with openpyxl.

I guess it comes from the "path" as I use:

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

How can I open my excel file that would be stored in a folder next to the .exe or include them in the setup.py ? I have a few models.

Thanks in advance for your help.


Solution

  • Well.. i found it in the cx_Freeze documentation, sorry ! posting answer if it helps, adding some comments for begginers like me:

    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)
    

    In filename, do not forget to include \ : "\aFolder\myFile.xlsx"

    It works well for me in replacement of my code above (without the function):

    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)