如何检查大型Excel文件是否受到尽快保护?

问题描述 投票:-1回答:3

如何以最快的方式检查excel文件是否受密码保护(无需尝试打开它并放置异常)?

更新:

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

一个问题是我得到了False作为输出,因此我无法摆脱该异常并将其替换为is_zipfile()条件。

python openpyxl win32com
3个回答
0
投票

使用openpyxl库的解决方案:

import openpyxl
wb = openpyxl.load_workbook(PATH_TO_FILE)

if wb.security.lockStructure == None:
    #  no password, act accordingly
    ...
else:
    #  password, act accordingly
    ...

0
投票

您可以使用工作表的protection._password属性执行此操作:

wb = openpyxl.load_workbook("C:\\Users\\...\\Downloads\\some_workbook.xlsx")

print(wb.worksheets[0].protection._password)

您可以根据工作簿中的工作表为所需的任何工作表执行此操作。

如果没有密码,则值为None。否则,它将返回哈希密码。

因此,您可以创建一种方法来检查此:

def password_protected(sheet):
   if sheet.protection._password is None:
      return False
   return True

相同的方法适用于整个工作簿,属性仅为workbook.protection._workbook_password


0
投票

[尝试使用openpyxl打开受密码保护的工作簿时,的确给出了一个zipfile.BadZipFile错误,因此可以使用一种解决方法:

import zipfile
zipfile.is_zipfile("workbook.xlsx")
© www.soinside.com 2019 - 2024. All rights reserved.