Search code examples
pythonxlwings

Hide the password to get data from a protected excel file without user intervention


I have a script that runs during the overnight in order to load some tables from my database. This scripts runs automatically (don't need any user interaction).

One of the modules is to get some data from a excel, that is a protected file and it requires a password.

To get the data from my file I am using the following code:

import xlwings as xw
PATH = 'filename.xlsx'
app = xw.App(visible=False)
wb = xw.Book(PATH, password='ASD')
sheet = wb.sheets['sheet']

My question is: there exists any other way to hide the password from the script? Maybe I am trying to get following code:

wb = xw.Book(PATH, password='******')

Any suggestion?


Solution

  • You would typically use an environment variable. For how to set one on Windows, see e.g. here.

    import os
    wb = xw.Book(PATH, password=os.environ['EXCEL_FILE_PASSWORD'])
    

    Note that this allows you to keep the password out of the source code, so it doesn't end up on your Git repo for example. But anybody who has access to the computer with the environment variable has also access to the content of it which is your password.