python 判断excel文件是否被加密

# 环境: win10/mac皆可,python 3.7

import pandas as pd
import os
import xlrd
fpath = r'/Users/.../test.xlsx' # mac环境
# fpath = r'C:/.../test.xlsx' win环境

filename = os.path.basename(fpath) # 获取文件名

try:
    df = pd.read_excel(fpath, sheet_name = 0)

except xlrd.biffh.XLRDError:
    print("该文件: %s 已被加密" %(filename))
    
# 若excel被加密,则打印 “该文件: test.xlsx 已被加密”

应用场景:

1.在不知道哪些excel文件已经加密的前提下,避免读取加密excel文件内容时报错

2.给定一个文件夹,运用递归调用加密函数,对该文件夹下(包括子文件夹下),所有未被加密的excel文件进行加密。若excel文件已经加密,则跳过不再加密(当然也可以调用gp让用户输入密码,进行重新加密)。

Python中,你可以使用pandas库结合pyodbc或openpyxl库来读写Excel文件,并通过第三方库如 cryptography 或 python-pptx (仅限于PowerPoint格式) 来实现加密功能。以下是基本步骤: 1. **安装必要的库**: - `cryptography` 提供了高级加密支持 - 如果需要对xlsx/xlsm/xltm文件操作,安装 `openpyxl` - 如果需要对pptx/ppsx文件操作,安装 `python-pptx` ```bash pip install cryptography openpyxl python-pptx ``` 2. **创建密钥对** (例如使用AES): ```python from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes key = b'some_random_key' cipher = Cipher(algorithms.AES(key), modes.CBC(b'some_initialization_vector')) ``` 3. **加密内容** (这里以DataFrame为例): ```python def encrypt_excel(df, output_file, password): # ...将df转换成适当的格式(例如XlsxWriter) writer = XlsxWriter(...) # 使用openpyxl或XlsxWriter # 加密工作簿 encrypted_writer = EncryptedZipFile(output_file, mode='w', encryption=zipfile.ZIP_DEFLATED, compression=zipfile.ZIP_STORED) encrypted_writer.setpassword(password.encode()) for sheet in df.iterrows(): encrypted_writer.writestr(sheet[0].name, sheet[1].to_string().encode()) encrypted_writer.close() ``` 4. **解密内容**: ```python def decrypt_excel(input_file, password): with EncryptedZipFile(input_file, mode='r') as encrypted_zip: encrypted_zip.setpassword(password.encode()) for name in encrypted_zip.namelist(): if name.endswith('.xlsx'): # 根据文件判断是否加密的工作簿 decrypted_data = encrypted_zip.read(name).decode() # 使用openpyxl读取并处理数据 workbook = load_workbook(io.BytesIO(decrypted_data)) # 接下来可以操作workbook中的sheet ``` 注意,这只是一个基础示例,实际应用中可能需要更复杂的错误处理和密码管理。同时,密码存储也需要安全,避免明文硬编码。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值