解密受密码保护XLS文件后,Pandas读取遇Unicode解码错误
解决受密码保护XLS文件解密后读取的编码错误
首先,解密完成后decrypted_workbook这个BytesIO对象的指针会停在文件末尾,pandas读取时会找不到内容,这是常见的遗漏点,先重置指针:
decrypted_workbook = io.BytesIO() with open(file_path, 'rb') as file: office_file = msoffcrypto.OfficeFile(file) office_file.load_key(password=password) office_file.decrypt(decrypted_workbook) decrypted_workbook.seek(0) # 关键:将文件指针移到开头 df = pd.read_excel(decrypted_workbook, engine='xlrd')
如果仍出现编码错误,注意XLS是旧版二进制Excel格式,pandas默认的openpyxl引擎不支持该格式,必须指定engine='xlrd'(需先安装兼容版本:pip install xlrd==1.2.0,新版xlrd已不再支持XLS)。
若上述方法无效,可尝试将解密后的内容写入临时文件再读取,绕开流读取的编码问题:
import io import msoffcrypto import pandas as pd import tempfile import os decrypted_workbook = io.BytesIO() with open(file_path, 'rb') as file: office_file = msoffcrypto.OfficeFile(file) office_file.load_key(password=password) office_file.decrypt(decrypted_workbook) # 写入临时文件 with tempfile.NamedTemporaryFile(suffix='.xls', delete=False) as tmp_file: tmp_file.write(decrypted_workbook.getvalue()) tmp_path = tmp_file.name # 读取临时文件 df = pd.read_excel(tmp_path, engine='xlrd') # 清理临时文件 os.unlink(tmp_path)
另外可先验证解密是否成功:将decrypted_workbook的内容保存为本地XLS文件,手动用Excel打开,若无法打开则说明解密环节存在问题(比如密码错误、文件损坏),需优先排查。
内容的提问来源于stack exchange,提问作者Elian Jose
相关产品推荐
相关产品推荐

