简体   繁体   中英

How to open / read password protected xls or xlsx (Excel) file using python in Linux?

I want to open password protected xls or xlsx using python. Generally I use xlrd to process xls or xlsx files but it cannot open password protected excel files. I tried to use pywin32 but I was not able to install it on my Linux system.

You can do that using a method outlined in my answer to a similar question.

It does not require Excel to be installed and, because it's pure Python, it's cross-platform too!

msoffcrypto-tool supports password-protected (encrypted) Microsoft Office documents, including the older XLS binary file format.

  • Install msoffcrypto-tool:

     pip install msoffcrypto-tool
  • You could create an unencrypted version of the workbook from the command line:

     msoffcrypto-tool Myfile.xlsx Myfile-decrypted.xlsx -p "caa team"
  • Or, you could use msoffcrypto-tool as a library. While you could write an unencrypted version to disk like above, you may prefer to create an decrypted in-memory file and pass this to your Python Excel library ( openpyxl , xlrd , etc.).

     import io import msoffcrypto import openpyxl decrypted_workbook = io.BytesIO() with open('Myfile.xlsx', 'rb') as file: office_file = msoffcrypto.OfficeFile(file) office_file.load_key(password='caa team') office_file.decrypt(decrypted_workbook) # `filename` can also be a file-like object. workbook = openpyxl.load_workbook(filename=decrypted_workbook)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM