openpyxl : I can't open excel file with password

Viewed 4532

I am a student.

I want to read protected excel file with openpyxl, but I can't.

This is my code.

    wb = load_workbook(file_path)  # Error returned in this line.
    wb.security.workbook_password = 'password'
    ws = wb.active

This is my error message

    Traceback (most recent call last):
  File "D:\env\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = get_response(request)
  File "D:\env\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "D:\env\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\env\lib\site-packages\django\views\generic\base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "D:\env\lib\site-packages\django\views\generic\base.py", line 88, in dispatch
    return handler(request, *args, **kwargs)
  File "D:\manager\views_payment.py", line 32, in post
    self.read_excel(tmp.payment_excel)
  File "D:\manager\views_payment.py", line 20, in read_excel
    wb = load_workbook(file_path)
  File "D:\env\lib\site-packages\openpyxl\reader\excel.py", line 171, in load_workbook
    archive = _validate_archive(filename)
  File "D:\env\lib\site-packages\openpyxl\reader\excel.py", line 121, in _validate_archive
    archive = ZipFile(f, 'r', ZIP_DEFLATED)
  File "c:\python36\Lib\zipfile.py", line 1100, in __init__
    self._RealGetContents()
  File "c:\python36\Lib\zipfile.py", line 1168, in _RealGetContents
    raise BadZipFile("File is not a zip file")
zipfile.BadZipFile: File is not a zip file

What is the problem?

1 Answers

To open an excel file with openpyxl, you need it do be in a unencrypted format (opening password-protected Excel files with openpyxl is not supported), so you would need to open the file manually and save it in an unencrypted format first, before calling it with openpyxl.

Related