gpt4 book ai didi

python - xlrd - 错误 "Workbook is encrypted",Python 3.2.3

转载 作者:行者123 更新时间:2023-12-03 10:02:43 24 4
gpt4 key购买 nike

我有一个简短的程序,它收集文件夹/子文件夹中所有 .xls 文件的列表,然后遍历文件列表,打开每个 xls 文档(尝试: book = xlrd.open_workbook(f) )以查找特定信息.如果抛出异常,我将文件名写到异常列表中。我发现我有很多 xlrd 抛出错误的文件:

Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
book = xlrd.open_workbook(f)
File "C:\Python32\lib\site-packages\xlrd\__init__.py", line 435, in open_workbook
ragged_rows=ragged_rows,
File "C:\Python32\lib\site-packages\xlrd\book.py", line 116, in open_workbook_xls
bk.parse_globals()
File "C:\Python32\lib\site-packages\xlrd\book.py", line 1206, in parse_globals
self.handle_filepass(data)
File "C:\Python32\lib\site-packages\xlrd\book.py", line 924, in handle_filepass
raise XLRDError("Workbook is encrypted")
xlrd.biffh.XLRDError: Workbook is encrypted

但我可以毫无问题地用 Excel 打开文件。有没有人知道为什么 xlrd 在文件似乎没有加密时会抛出加密错误?

谢谢,

弗雷德

最佳答案

我遇到了同样的问题,正如@zindorsky 在他们的评论中提到的那样,当文件具有 protected 工作表时可能会发生这种情况 - 或者由于 Excel 使用魔术密码静默加密文件的其他原因 VelvetSweatshop .

XLRD 无法单独处理加密文件(实际上 README 将其列为“不太可能完成”),但最近有另一个 Python 库可以解密各种 MS Office 文件(包括 .xls 文件) ) - msoffcrypto-tool .

我能够使用它成功解决该问题 - 这是代码的缩写(且未经测试!)片段版本

import xlrd
import msoffcrypto

def handle_protected_workbook(wb_filepath):
try:
_book = xlrd.open_workbook(wb_filepath)
except xlrd.biffh.XLRDError, e:
if e.message == "Workbook is encrypted":
# Try and unencrypt workbook with magic password
wb_msoffcrypto_file = msoffcrypto.OfficeFile(open(wb_filepath, 'rb'))
try:
# Yes, this is actually a thing
# https://nakedsecurity.sophos.com/2013/04/11/password-excel-velvet-sweatshop/
wb_msoffcrypto_file.load_key(password='VelvetSweatshop')
except AssertionError, e:
if e.message == "Failed to verify password":
# Encrypted with some other password
raise # or do something else
else:
# Some other error occurred
raise
except:
# Some other error occurred
raise
else:
# Magic Excel password worked

assert wb_filepath.endswith('.xls')
wb_unencrypted_filename = wb_filepath[:-(len('.xls'))] + '__unencrypted.xls'

with tempfile.NamedTemporaryFile() as tmp_wb_unencrypted_file:
# Decrypt into the tempfile
wb_msoffcrypto_file.decrypt(tmp_wb_unencrypted_file)
# --- Do something with the file ---
# return true to indicate file was touched
return True # or do something else
else:
# some other xlrd error occurred.
return False # or do something else
except:
# some non-xlrd error occurred.
return False # or do something else

关于python - xlrd - 错误 "Workbook is encrypted",Python 3.2.3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22789951/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com