You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python无需用户输入读取受密码保护的Excel文件?

如何在无需用户输入的情况下用Python读取受密码保护的Excel文件

一、改进解密-加密方案(无需手动输入密码)

你找到的方案可以修改为无需手动输入密码,只需将密码预先存入变量(或从配置文件、环境变量读取),调用函数时直接传入即可。修改后的代码如下:

import win32com.client as win32
import pandas as pd

# 建议从环境变量/配置文件读取,避免硬编码密码
EXCEL_PASSWORD = "你的文件密码"

def unprotect_xlsx(filename, pw_str):
    xcl = win32.Dispatch("Excel.Application")
    xcl.Visible = False  # 隐藏Excel窗口,避免弹窗干扰
    wb = xcl.Workbooks.Open(filename, False, False, None, pw_str)
    xcl.DisplayAlerts = False
    wb.SaveAs(filename, None, '', '')  # 保存为无密码版本
    xcl.DisplayAlerts = True
    xcl.Quit()

def protect_xlsx(filename, pw_str):
    xcl = win32.Dispatch("Excel.Application")
    xcl.Visible = False
    wb = xcl.Workbooks.Open(filename)
    xcl.DisplayAlerts = False
    wb.SaveAs(filename, None, '', pw_str)  # 重新加密文件
    xcl.DisplayAlerts = True
    xcl.Quit()

# 使用流程:解密→读取→重新加密
unprotect_xlsx("目标文件路径.xlsx", EXCEL_PASSWORD)
df = pd.read_excel("目标文件路径.xlsx")
protect_xlsx("目标文件路径.xlsx", EXCEL_PASSWORD)

注意事项:

  • 需安装依赖:pip install pywin32 pandas
  • 仅支持Windows系统,依赖本地Excel COM组件
  • 操作会修改原文件,建议提前备份

二、无需解密再加密,直接用Pandas读取的方法

根据Excel密码的类型,分两种场景处理:

1. 工作簿打开密码(必须输入密码才能打开文件)

使用msoffcrypto-tool库解密文件流,直接在内存中传递给Pandas,无需保存解密后的文件到磁盘:

import msoffcrypto
import pandas as pd
from io import BytesIO

EXCEL_PASSWORD = "你的文件密码"

with open("目标文件路径.xlsx", "rb") as f:
    office_file = msoffcrypto.OfficeFile(f)
    office_file.load_key(password=EXCEL_PASSWORD)
    # 将解密后的内容写入内存流
    decrypted_stream = BytesIO()
    office_file.decrypt(decrypted_stream)
    # 重置流指针到起始位置
    decrypted_stream.seek(0)
    # 用Pandas读取解密后的内容
    df = pd.read_excel(decrypted_stream, engine="openpyxl")

安装依赖:pip install msoffcrypto-tool pandas openpyxl

2. 工作表保护密码(文件可打开,但工作表被锁定无法编辑)

这种情况下Pandas可以直接读取工作表内容;如果需要编辑内容,可先用openpyxl移除保护:

from openpyxl import load_workbook
import pandas as pd
from io import BytesIO

EXCEL_PASSWORD = "工作表保护密码"

# 加载工作簿并移除工作表保护
wb = load_workbook("目标文件路径.xlsx")
for sheet_name in wb.sheetnames:
    ws = wb[sheet_name]
    ws.protection.unprotect(EXCEL_PASSWORD)

# 将修改后的工作簿写入内存流
buffer = BytesIO()
wb.save(buffer)
buffer.seek(0)

# 用Pandas读取内容
df = pd.read_excel(buffer)

总结

  • 针对工作簿打开密码:优先用msoffcrypto-tool内存解密,避免修改原文件
  • 针对工作表保护密码:Pandas可直接读取,如需编辑再用openpyxl移除保护
  • 密码尽量从环境变量或配置文件读取,不要硬编码在代码中

内容的提问来源于stack exchange,提问作者J_B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 08:03:34