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

在Databricks中用Python为S3的Excel(.xlsx)文件设置密码保护

解决Excel文件密码保护无效的问题

问题原因

原代码的核心问题:

  • openpyxl和xlsxwriter不支持设置文件级的打开密码,它们仅能设置工作表的编辑限制(比如禁止修改单元格),无法实现打开文件时需输入密码的效果。
  • 你的代码里甚至没有尝试设置任何保护逻辑,只是加载并保存了文件,自然不会有密码保护效果。

正确解决方案

使用msoffcrypto-tool库,它专门用于处理Office文档的加密和解密,支持设置Excel文件的打开密码。

步骤1:安装依赖

在Databricks环境中运行以下命令安装库:

%pip install msoffcrypto-tool

步骤2:修改代码实现加密

以下是完整的工作代码,包含从S3挂载路径读取文件、加密、保存回S3的逻辑:

import msoffcrypto
import shutil
from io import BytesIO

def password_protect_excel(input_path, output_path, password):
    # 读取源文件二进制内容
    with open(input_path, "rb") as f:
        file_content = f.read()
    
    # 加载文件并设置打开密码
    excel_file = msoffcrypto.OfficeFile(BytesIO(file_content))
    excel_file.set_password(password)
    
    # 将加密后的内容写入临时文件
    temp_local_path = "/tmp/Report_protected_temp.xlsx"
    with open(temp_local_path, "wb") as f:
        excel_file.save(f)
    
    # 将加密文件复制到S3挂载目标路径
    shutil.copy(temp_local_path, output_path)
    print(f"加密后的文件已保存到: {output_path}")

if __name__ == "__main__":
    input_file = "/dbfs/mnt/file_mount_report/Report.xlsx"
    output_file = "/dbfs/mnt/file_mount_report/Report_protected_new.xlsx"
    password = "your_strong_password"
    
    password_protect_excel(input_file, output_file, password)

代码说明

  1. 读取文件:从S3挂载路径读取原始Excel文件的二进制内容,避免直接操作挂载路径的权限问题。
  2. 设置密码:通过msoffcrypto.OfficeFile加载文件,调用set_password()设置文件级打开密码。
  3. 保存加密文件:先将加密后的内容写入本地临时文件,再复制到S3挂载路径,确保文件写入稳定。

验证效果

加密后的文件打开时,Excel会弹出密码输入框,只有输入正确密码才能查看文件内容,完全符合预期的保护需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 03:34:54