如何用 Python 读取带密码的 Excel 表?

python 有哪些方式可以读取带密码的 excel ?
另外,pandas 可以吗?
如何用 Python 读取带密码的 Excel 表?

2 回复
import pandas as pd
from msoffcrypto import OfficeFile
import io

def read_protected_excel(file_path, password):
    """
    读取受密码保护的Excel文件
    
    参数:
        file_path: Excel文件路径
        password: 文件密码
        
    返回:
        pandas DataFrame 或 None
    """
    try:
        # 使用msoffcrypto库解密文件
        with open(file_path, "rb") as f:
            office_file = OfficeFile(f)
            
            # 检查文件是否加密
            if office_file.is_encrypted():
                # 使用密码解密
                office_file.load_key(password=password)
                
                # 将解密后的数据读取到内存中
                decrypted = io.BytesIO()
                office_file.decrypt(decrypted)
                
                # 重置指针位置
                decrypted.seek(0)
                
                # 使用pandas读取解密后的数据
                df = pd.read_excel(decrypted)
                return df
            else:
                print("文件未加密,直接读取")
                return pd.read_excel(file_path)
                
    except Exception as e:
        print(f"读取文件时出错: {e}")
        return None

# 使用示例
if __name__ == "__main__":
    # 替换为你的文件路径和密码
    excel_path = "protected_file.xlsx"
    file_password = "your_password_here"
    
    # 读取加密的Excel文件
    data = read_protected_excel(excel_path, file_password)
    
    if data is not None:
        print("成功读取数据:")
        print(data.head())
    else:
        print("读取失败,请检查文件路径和密码")

需要安装的库:

pip install pandas openpyxl msoffcrypto-tool

代码说明:

  1. 使用msoffcrypto库处理Excel文件的加密解密
  2. 先用密码解密文件到内存缓冲区
  3. 再用pandas读取解密后的数据
  4. 包含错误处理,如果文件未加密会直接读取

注意: 这个方法适用于.xlsx格式的文件,如果是.xls格式可能需要使用其他库。

一句话建议:用msoffcrypto解密后再用pandas读取。


用 win32com 就可以了。
pandas 应该不行。

回到顶部