问题
How to check if excel file is protected with password the fastest way (without trying to open it and placing an exception)?
Updated:
from zipfile import *
from openpyxl import load_workbook
filename = 'Z:\\path_to_file\\qwerty.xlsm' # protected one
try:
wb = load_workbook(filename, data_only=True, read_only=True)
except (BadZipfile) as error:
print(is_zipfile(filename))
A problem is that I got False as an output, thus I cannot get rid of the exception and replace it with is_zipfile() condition.
回答1:
Solution using the openpyxl library:
import openpyxl
wb = openpyxl.load_workbook(PATH_TO_FILE)
if wb.security.lockStructure == None:
# no password, act accordingly
...
else:
# password, act accordingly
...
回答2:
You can do this using the protection._password property of a sheet:
wb = openpyxl.load_workbook("C:\\Users\\...\\Downloads\\some_workbook.xlsx")
print(wb.worksheets[0].protection._password)
You can do this for whatever sheet you would like, based off the worksheets in the workbook.
If there is no password, the value is None. Otherwise, it returns the hashed password.
So, you can create a method to check this:
def password_protected(sheet):
if sheet.protection._password is None:
return False
return True
The same method applies for the whole workbook, the property is just workbook.protection._workbook_password.
回答3:
When trying to open a password protected workbook with openpyxl, this indeed gives a error zipfile.BadZipFile so a workaround would be to use:
import zipfile
zipfile.is_zipfile("workbook.xlsx")
来源:https://stackoverflow.com/questions/54558302/how-to-check-if-a-large-excel-file-is-protected-as-quickly-as-possible