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.性能:

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

相关推荐
JordanHaidee20 小时前
Python 中 `if x:` 到底在判断什么?
后端·python
ServBay21 小时前
10分钟彻底终结冗长代码,Python f-string 让你重获编程自由
后端·python
闲云一鹤21 小时前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
Rockbean1 天前
用40行代码搭建自己的无服务器OCR
服务器·python·deepseek
曲幽1 天前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi
用户60648767188961 天前
国内开发者如何接入 Claude API?中转站方案实战指南(Python/Node.js 完整示例)
人工智能·python·api
只与明月听1 天前
RAG深入学习之Chunk
前端·人工智能·python
用户8356290780511 天前
自动化文档处理:Python 批量提取 PDF 图片
后端·python
多恩Stone2 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054962 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django