cat_on_the_mat
cat_on_the_mat

Reputation: 120

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

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.

Upvotes: 3

Views: 3750

Answers (3)

Juta
Juta

Reputation: 411

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")

Upvotes: 0

Nick
Nick

Reputation: 898

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.

Upvotes: 0

Python Newb
Python Newb

Reputation: 89

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
    ...

Upvotes: 0

Related Questions