0
from openpyxl.workbook.protection import WorkbookProtection
import openpyxl as xl
wb = xl.load_workbook(path, keep_vba=True)

wb.security = WorkbookProtection()
wb.security.workbookPassword = 'test_password'
wb.security.lockStructure = True

ws = wb.active
# some code 
wb.save(filename=path)

I tried to use the code above to password-protect an Excel file. There is no error but there is also no password prompt.

Can anyone help?

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
pynew
  • 21
  • 1
  • 7
  • Please provide more details. What do you mean by no password request? – Anupam Chaplot Feb 10 '20 at 04:17
  • I want to set a password when export an excel, so than other user may need a password to access the workbook – pynew Feb 10 '20 at 05:48
  • @EmrahDiril No =L= – pynew Feb 10 '20 at 05:59
  • You want to put a password when *opening* an Excel file? Because [openpyxl]'s `WorkbookProtection` only works for preventing modifying sheets, etc. – Gino Mempin Feb 10 '20 at 07:28
  • @GinoMempin Yes,as you know, any other way can do that? since the content is kind of confidential – pynew Feb 10 '20 at 09:15
  • I can protect the sheets right now, maybe just hidden content if the password not been enter, however i don't know how to check the password have been enter or not – pynew Feb 10 '20 at 09:21
  • I don't think there's a way for `openpyxl` to put a password on opening the file. It only offers [basic protection](https://openpyxl.readthedocs.io/en/stable/protection.html): "*“Worksheet or workbook element protection should not be confused with file security. It is meant to make your workbook safe from unintentional modification...*". You'll have to consider alternative solutions, such as zipping-up the excel file then password-protecting that zip file, or converting the excel to a PDF then password-protecting the PDF. – Gino Mempin Feb 11 '20 at 02:33
  • Why don't you make python ask for a password and then simply open the file if it is correct? – Filip Feb 11 '20 at 02:41
  • Because I can only send excel to other pepole and they don't use python... – pynew Feb 11 '20 at 02:49
  • @GinoMempin After google, zip with password is a easy way. But... maybe other library/module that i don't know can handle the encrypt? Thank you for your suggestion !!!!!!!! – pynew Feb 11 '20 at 03:00
  • There's a *very* limited number of Python libraries that can handle Excel files: openpyxl, xlsxwriter, xlwings. None of them though offers the function that you need. I would use a different way for serving the data, something that has password protection support. – Gino Mempin Feb 11 '20 at 05:35

0 Answers0