如何使用 Python 检测 Excel 文件中受保护的单元格?

How to detect protected cells in Excel file using Python?

鉴于 Excel 文件包含一些受密码保护的单元格,我想检测这些受保护的单元格以选择是将它们包含在输入中还是跳过它们。

我试过了pandas

df = pd.read_excel('test.xlsx', engine='openpyxl')

openpyxl

wb = openpyxl.load_workbook('test.xlsx')
sheet = wb['Sheet1']
# B4 is a protected cell with a specific password so I cannot change its value in
# the Excel file without the password
print(sheet['B4'].value)
>> 8
sheet['B4'].value = 7
print(sheet['B4'].value)
>> 7

但是,受保护的单元格可以像其他未受保护的单元格一样正常读取,并且可以轻松更改。

所以问题是,我怎样才能检测到这些受保护的细胞?

例如,是否有任何方法可以读取指示单元格是否受保护的 Excel 文件的属性?

使用openpyxl,您可以通过其protection属性检测每个单元格的锁定或隐藏状态,例如:

>>> sheet['B4'].protection.locked
True
>>> sheet['B4'].protection.hidden
False