How to check if a large Excel file is protected as quickly as possible?

懵懂的女人 提交于 2020-02-29 09:10:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!