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

Openpyxl 3.0.9设置Excel打开密码报错AttributeError的解决求助

问题描述

本人已参考相关Stack Overflow帖子,请勿标记为重复。

我使用Openpyxl 3.0.9版本,在对Excel完成操作后尝试设置打开密码,编写了如下代码:

for search, v in merge_df.groupby(['Country']):
    writer = pd.ExcelWriter(f"BC_{Country}.xlsx", engine='xlsxwriter')
    v.to_excel(writer,columns=col_list,sheet_name=f'BC_{Country}',index=False, startrow = 1)
    wb1 = load_workbook(filename = f"BC_{Country}.xlsx")
    sheet_to = wb1.worksheets[0]
    wb1.security.workbookPassword = "test"
    wb1.save(f"BC_{Country}.xlsx")

运行时出现错误:

AttributeError: 'NoneType' object has no attribute 'workbookPassword'

请问如何设置密码,让用户必须输入密码才能打开Excel文件?

解决方案

为啥会报错?

wb1.security默认是None,因为openpyxl的Workbook.security仅用于设置工作簿结构保护(比如禁止删除/添加工作表),根本不是用来设置文件打开密码的。直接访问workbookPassword自然会触发NoneType错误。

划重点:Openpyxl搞不定文件打开密码

Openpyxl本身没有实现加密整个Excel文件的功能,它的安全设置只针对工作簿结构或工作表内容的权限控制,没法设置打开文件必须输入的密码。

靠谱的实现方法

要给Excel文件加打开密码,推荐用msoffcrypto-tool库,它专门处理Office文档的加密解密。步骤如下:

  1. 先安装依赖:
pip install msoffcrypto-tool pandas openpyxl
  1. 修改代码逻辑:先正常生成未加密的Excel文件,再用这个库加密:
import msoffcrypto
import pandas as pd
import io

for Country, v in merge_df.groupby(['Country']):
    # 第一步:生成未加密的Excel文件
    file_path = f"BC_{Country}.xlsx"
    writer = pd.ExcelWriter(file_path, engine='xlsxwriter')
    v.to_excel(writer, columns=col_list, sheet_name=f'BC_{Country}', index=False, startrow=1)
    writer.close()  # 必须关闭writer才能确保文件写入完成
    
    # 第二步:加密文件
    with open(file_path, "rb") as f_in:
        file_data = io.BytesIO(f_in.read())
    
    office_file = msoffcrypto.OfficeFile(file_data)
    office_file.load_key(password="test")  # 设置密码
    
    # 保存加密后的文件,直接覆盖原文件即可
    with open(file_path, "wb") as f_out:
        office_file.encrypt(f_out, password="test")

另一种方法(仅限Windows环境)

如果你用的是Windows系统,也可以调用Excel本身的COM对象来实现加密:

import win32com.client as win32
import pandas as pd

for Country, v in merge_df.groupby(['Country']):
    file_path = f"BC_{Country}.xlsx"
    # 先生成Excel文件
    writer = pd.ExcelWriter(file_path, engine='xlsxwriter')
    v.to_excel(writer, columns=col_list, sheet_name=f'BC_{Country}', index=False, startrow=1)
    writer.close()
    
    # 调用Excel加密
    excel = win32.Dispatch("Excel.Application")
    excel.Visible = False  # 后台运行不显示Excel窗口
    wb = excel.Workbooks.Open(file_path)
    wb.SaveAs(file_path, Password="test")
    wb.Close()
    excel.Quit()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 09:18:13