分享

办公自动化:python win32com轻松完成批量Excel文件的加密!

 Python集中营 2023-02-27 发布于甘肃

在办公的过程中面对一些重要数据的加密通常都能够借助wps/office来完成,但是面对批量处理的时候还是有些麻烦。

本篇文章主要说明如何使用python的三方模块完成对Excel文件的批量加密操作。

其中主要使用到的三方模块就是win32com,这里需要注意的是在安装该库的时候对应的名称是pywin32。pip install pywin32

接下来,将需要的几个python模块都导入到代码块中进行后续的业务开发。# It's importing the win32com.client module.

import win32com.client

# Importing the os module.

import os

from loguru import logger

然后,开发一个单个文件的加密函数excel_set_password_one完成文件加密操作。def excel_set_password_one(source_file_path, target_file_path, password):

"""

It takes an Excel file, sets a password on it, and saves it to a new file.

:param source_file_path: The path to the Excel file you want to set a password on

:param target_file_path: The path to the file you want to save the password-protected file to

:param password: the password you want to set for the excel file

"""

excel = win32com.client.Dispatch("Excel.Application")

# It's opening the Excel file.

wb = excel.Workbooks.Open(source_file_path, False, False, None, '')

# It's turning off the alert that pops up when you try to save a file with a password.

excel.DisplayAlerts = False

# It's saving the file to a new file with a password.

wb.SaveAs(target_file_path, None, password, '')

# It's closing the Excel application.

excel.Quit()

单个excel文件加密过程开发完成之后,需要再创建一个函数batch_main可以完成批量执行每个excel文件加密的操作。def batch_main(batch_dir, password):

"""

This function takes a directory of files and a password, and then encrypts all the files in the directory with the

password

:param batch_dir: The directory where the batch files are located

:param password: The password to use for the encrypted zip file

"""

logger.info('批量处理Excel文件加密过程开始!')

if batch_dir is None or batch_dir.strip() == '':

logger.debug('批量处理的文件路径不能为空!')

return

if password is None or password.strip() == '':

logger.debug('批量处理的文件加密路径不能为空!')

return

for file_name in os.listdir(batch_dir):

if file_name.__contains__('xlsx'):

source_file_path = os.path.join(batch_dir, file_name)

target_file_path = os.path.join(batch_dir, file_name.split('.')[0] + '_已加密.xlsx')

excel_set_password_one(source_file_path, target_file_path, password)

logger.info('批量处理Excel文件加密过程完成!')

最后一步,使用main函数调用批量文件加密的batch_main函数即可完成对所有该文件夹下面的文件加密。if __name__ == '__main__':

batch_main('D:/test-data-work', '123456')

D:\Python\Python311\python.exe D:\pycharm-projects\the-public\test020\test7.py

2023-01-19 10:35:36.799 | INFO     | __main__:batch_main:64 - 批量处理Excel文件加密过程开始!

2023-01-19 10:35:40.529 | INFO     | __main__:batch_main:77 - 批量处理Excel文件加密过程完成!

「Python 集中营」,只做知识分享 !历

ChatGPT为何能够引流潮流,成为最受追捧的AI神器?

办公自动化:python能够轻松完成网络测速的几种操作方式!

如何使用python AI快速比对两张人脸图像?

python项目环境迁移时如何生成第三方库文件requirements.txt并安装?

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多