msoffcrypto-tool库 Excel 加密

一、安装 msoffcrypto-tool

注意: 运行前请确保已执行 pip install msoffcrypto-tool。

二、抽取函数

python 复制代码
import pandas as pd
import msoffcrypto
import io
def encrypt_excel_buffer(buffer, filename, password):
    """
    将内存中的 Excel 数据加密并保存到磁盘
    """
    buffer.seek(0)
    office_file = msoffcrypto.OfficeFile(buffer)
    with open(filename, "wb") as f_out:
        office_file.encrypt(password=password, outfile=f_out)
    buffer.close()

三、先将数据全部写进内存 buffer,关闭 writer 后再加密输出到磁盘。

python 复制代码
for i in ['1','2','3']:
    # 1. 创建内存缓冲区
    buffer = io.BytesIO()
    
    # 2. 将数据写入内存缓冲区而不是直接写磁盘
    with pd.ExcelWriter(buffer, engine='openpyxl') as writer:
        # 写入第一个 Sheet
        df_fh = wnrfh[wnrfh['统筹区'] == i]
        df_fh.to_excel(writer, sheet_name='符合导入', index=False)
        
        # 写入第二个 Sheet
        df_tc = wnrtc[wnrtc['统筹区'] == i]
        df_tc.to_excel(writer, sheet_name='存在个单', index=False)
    
    # 3. 调用加密函数,将内存数据变成加密文件保存
    target_filename = f'未缴费纳入统计审核通过-{i}.xlsx'
    encrypt_excel_buffer(buffer, target_filename, password="你的密码")
print("所有统筹区文件已加密生成。")

1.with 语句的作用:

在 with pd.ExcelWriter... 结束时,Pandas 会自动完成 Excel 的结构构建并将其"保存"到 buffer 中。只有在 writer 关闭后,buffer 里的内容才是完整的 Excel 文件。

2.避免磁盘残留:

通过 io.BytesIO(),整个过程中没有任何一个时刻会在磁盘上产生"不带密码"的临时文件,安全性最高。

3.文件名处理:

使用了 Python 的 f-string (f'...'),比 .format() 更简洁,适合 2026 年的主流写法。

4.性能:

此方法在内存中操作,对于几万行以内的数据,速度会比先写磁盘再加密快很多。

相关推荐
MartinYeung56 分钟前
[论文学习]MPIB:医疗提示注入基准——针对LLM临床安全性的系统性评估
人工智能·python·学习
用户8356290780519 分钟前
使用 Python 为 PowerPoint 演示文稿添加评论
后端·python
阿图灵38 分钟前
OpenCV 绘图五件套:画圆、文本、线段、矩形与椭圆
图像处理·人工智能·python·opencv·计算机视觉·绘图
web行路人44 分钟前
AI全栈之旅 · 第一周总结
python
slacker-kian1 小时前
HuggingFace API加载模型超时:用 ModelScopeAPI 替代
人工智能·python·transformer·huggingface·blip·modelscope·blipprocessor
七夜zippoe1 小时前
DolphinDB 高可用部署实战:从容灾设计到故障自动转移
开发语言·python·高可用·容灾·dolphindb
l1258651 小时前
# LangGraph Deep Research Agent 全流程设计:多轮研究、人机协同与真实来源管理
数据库·人工智能·python·算法·自然语言处理·oracle·langchain
青少儿编程课堂2 小时前
图形化编程实战:智能交通灯调度台,一个作品讲透循环、条件与广播
c++·python·算法·bfs·信息学竞赛
HAPPY酷2 小时前
python的对象和方法
开发语言·python
the局外人2 小时前
别再背 Chain、Agent、Memory 了:用一条“智能流水线”学会 LangChain
python·langchain·llm