0

I am trying to find a way to edit a password protected excel with Python. Password is not required to open the excel, it is only required if you want to edit it:

Is it possible to access this using password and edit it? Would be perfect if it would be possible to edit it using Openpyxl. I have already tried to use msoffcrypto:

decrypted = io.BytesIO()

with open("encrypted.xlsx", "rb") as f:
    file = msoffcrypto.OfficeFile(f)
    file.load_key(password="Passw0rd")  # Use password
    file.decrypt(decrypted)

df = pd.read_excel(decrypted)

But I think this works only when you can access the file only with password (the whole file is password encrypted, not the edit part.

Kirilas
  • 43
  • 5
  • With Xlwings yes, see here for the options https://stackoverflow.com/questions/71267540/xlwings-open-password-protected-worksheet-in-xlsx – moken Jan 10 '23 at 23:27
  • Did you try your code, any error output you can share? – hc_dev Jan 11 '23 at 07:33
  • @hc_dev - yes, I receive following error: "Unencrypted document or unsupported file format". – Kirilas Jan 18 '23 at 06:27

1 Answers1

0

If the Excel workbook has been saved with a "Password to modify" like in Office 2011 then you you usually need to perform following steps in Excel to save an unprotected version:

  1. enter the password
  2. open the workbook (still it is write-protected)
  3. save as (unprotected)

In Python

You can decrypt it using a password and then pass the decrypted byte stream - as file-like object - to the opening function, be it pandas.read_excel() or openpyxl.load_workbook():

import io

import msoffcrypto
import openpyxl


decrypted_workbook = io.BytesIO()

with open('encrypted.xlsx', 'rb') as file:
    office_file = msoffcrypto.OfficeFile(file)
    office_file.load_key(password='passw0rd')
    office_file.decrypt(decrypted_workbook)

# `filename` can also be a file-like object.
workbook = openpyxl.load_workbook(filename=decrypted_workbook)

See also:

hc_dev
  • 8,389
  • 1
  • 26
  • 38
  • Sadly, none of these are able to modify a read-only password protected document (it is not considered as encrypted as I understand) since it can be opened like any other unencrypted document, the only difference that if you want to modify it you need to enter a password. – Kirilas Jan 23 '23 at 13:05