python如何完成对 Excel文件的解密后读取?

通常为了防止重要的Excel文件数据内容的泄露,需要对文件整体进行加密与解密的操作。

对于文件的加解密过程,python也有很多非标准库来帮助我们完成操作,这里主要说明如何完成对Excel文件的解密与读取操作。

这里我们使用到的是msoffcrypto-tool非标准库,可以选择使用pip的方式安装一下即可。

pip intall msoffcrypto-tool

该msoffcrypto-tool模块提供了代码层面的解密操作,也提供了CLI终端命令直接解密的操作。

1.使用终端命令

通过在终端命令行输入下面的命令即可完成对Office文件解密操作。

msoffcrypto-tool '加密文件路径' '解密文件路径' -p 123456

其中利用-p参数设置123456为解密文件需要的密码,可以使用该密码来完成解密操作。

2.使用python API

将示例中需要的解密的python模块都导入到当前的代码块中。

# Importing the pandas module and renaming it as pd.
import pandas as pd

# Importing the msoffcrypto module and renaming it as pto.
import msoffcrypto as pto

开始进行解密操作之前,我们首先将加密后的excel原始文件读取为File文件对象。

# Opening the file in binary mode.
file_ = pto.OfficeFile(open('D:/test/data.xlsx', 'rb'))

其次,对File文件对象设置文件解密时需要的密码,使用load_key函数加载密码。

# Loading the password into the file object.
file_.load_key(password='123456')

然后,同样使用File文件对象的decrypt函数可以完成对Excel文件的解密操作。

# Decrypting the file and saving it to the path specified.
file_.decrypt(open('./data_decrypted.xlsx', 'wb'))

至此,文件解密过程已经完成了,接下来只需要对生成的没有密码的新文件进行操作就可以了。

这里我们使用常用的pandas模块完成了对数据的读取操作就OK了。

# Reading the excel file and storing it in a dataframe.
data_frame = pd.read_excel('./data_decrypted.xlsx')

# Printing the dataframe.
print(data_frame)

关于更多的详细内容可以参考github上面作者对于msoffcrypto相关的详细说明。

https://github.com/nolze/msoffcrypto-tool
往期精彩

python最好用的能源类可视化图表模块,没有之一!

如何解决python读取大数据量文件时造成的内存溢出?

python情感分析:基于jieba的分词及snownlp的情感分析!

猜你喜欢

转载自blog.csdn.net/chengxuyuan_110/article/details/129015900
今日推荐