#转轮机密码窗口def create_new_window1 def encrypt_fileinput_file_path output_file_path key # 根据输入文件的后缀选择合适的加密函数 if input_file_pathendswithdocx # 如果是docx文件使用Python库docx对文本进行加密
在原有代码的基础上,添加以下代码段,使用Python库openpyxl对.xlsx文件进行加密和解密操作:
elif input_file_path.endswith('.xlsx'):
# 如果是.xlsx文件,使用Python库openpyxl对单元格数据进行加密或解密
workbook = load_workbook(input_file_path)
for sheet in workbook.sheetnames:
worksheet = workbook[sheet]
for row in worksheet.iter_rows():
for cell in row:
if cell.value is None:
continue
if isinstance(cell.value, str):
encrypted_value = encrypt_text(cell.value, key) #调用encrypt_text函数进行加密操作
cell.value = encrypted_value #将加密后的值赋给单元格
elif isinstance(cell.value, int) or isinstance(cell.value, float):
encrypted_value = encrypt_number(cell.value, key) #调用encrypt_number函数进行加密操作
cell.value = encrypted_value #将加密后的值赋给单元格
workbook.save(output_file_path) #保存加密后的文件
elif output_file_path.endswith('.xlsx'):
# 如果是.xlsx文件,使用Python库openpyxl对单元格数据进行解密
workbook = load_workbook(input_file_path)
for sheet in workbook.sheetnames:
worksheet = workbook[sheet]
for row in worksheet.iter_rows():
for cell in row:
if cell.value is None:
continue
if isinstance(cell.value, str):
decrypted_value = decrypt_text(cell.value, key) #调用decrypt_text函数进行解密操作
cell.value = decrypted_value #将解密后的值赋给单元格
elif isinstance(cell.value, int) or isinstance(cell.value, float):
decrypted_value = decrypt_number(cell.value, key) #调用decrypt_number函数进行解密操作
cell.value = decrypted_value #将解密后的值赋给单元格
workbook.save(output_file_path) #保存解密后的文件
需要在代码开始处添加以下函数,用于对数字进行加密和解密操作:
def encrypt_number(number, key):
# 将数字转换为字符串,并在前面加上'N'标识数字类型
number_str = 'N' + str(number)
# 调用encrypt_text函数进行加密操作
encrypted_text = encrypt_text(number_str, key)
return encrypted_text
def decrypt_number(text, key):
# 调用decrypt_text函数进行解密操作
decrypted_text = decrypt_text(text, key)
# 提取出数字部分并转换为数字类型
number = float(decrypted_text[1:])
return number
``
原文地址: https://www.cveoy.top/t/topic/ho2L 著作权归作者所有。请勿转载和采集!