Search code examples
pythonpython-3.xopenpyxlxlsxpassword-protection

How to detect if the xlsx file is password protected or not in python?


I have a required where I need to detect if the excel file is password protected or not. If password protected ask user for the password. How do I do this in python? I looked a bit on the internet, none of the answers were useful so far


Solution

  • You could do something along these lines I guess.
    If the file is encrypted it will pass and the password can be requested.
    If it's not, it will error and the file can be loaded normally.

    import openpyxl
    import io
    import msoffcrypto
    from msoffcrypto.exceptions import FileFormatError  # pip install msoffcrypto-tool
    
    filename = 'foo.xlsx'
    
    with open(filename, 'rb') as file:
        try:
            workbook = io.BytesIO()
            office_file = msoffcrypto.OfficeFile(file)
            print("File is password protected")
            passwd = input("Please enter file password")
            office_file.load_key(password=passwd)
            office_file.decrypt(workbook)
        except FileFormatError as e:
            print(e)
            print("File is not password protected")
            workbook=filename
    
        wb = openpyxl.load_workbook(workbook)
        ws = wb['Sheet1']
    
        print(ws['A1'].value)