解密后无法读取 xls(受密码保护的文件)

问题描述 投票:0回答:1
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)

df = pd.read_excel(decrypted_workbook)

我有一个受密码保护的 xls 文件,我尝试使用 msoffcrypto.OfficeFile() 对其进行解密。 现在,当我尝试读取解密的文件时,它给出了以下错误:

UnicodeDecodeError: 'utf-16-le' codec can't decode bytes in position 52-53: illegal UTF-16 surrogate

我本来希望将解密的文件作为工作簿来阅读。我尝试指定

df = pd.read_excel(decrypted_workbook)
df = pd.read_excel(decrypted_workbook,encoding = "utf-8") 

我也尝试过

df = pd.read_excel(decrypted_workbook, encoding = "utf-16")

他们都没有工作

python dataframe xls password-protection
1个回答
0
投票

尝试这样。

import msoffcrypto
import io
import pandas as pd

decrypted = io.BytesIO()

with open("test_encrypted.xlsx", "rb") as f:
    file = msoffcrypto.OfficeFile(f)
    file.load_key(password="test")  # Use password
    try:
        file.decrypt(decrypted)
        # Create an ExcelFile object
        xls_file = pd.ExcelFile(decrypted)

        # Print sheet names to verify
        print(xls_file.sheet_names)

    except msoffcrypto.exceptions.InvalidKeyError:
        print('The password is incorrect..')

如果仍然不起作用,则文件可能已损坏。

© www.soinside.com 2019 - 2024. All rights reserved.