#解决warning: UserWarning: Workbook contains no default style, apply openpyxl's default
import warnings
warnings.simplefilter('ignore')
import pandas as pd # 读取Excel并进行数据分析
import msoffcrypto # 读取加密的Excel文件
import io # 将文件写入到内存中
# 定义一个函数,用来导入Excel文件,并将获取的dataFrame数据结构返回
def read_excel(path, sheet_name, title, header=0, password=''):
decrypted = io.BytesIO() # 用来后来将读取到的Excel文件解密之后写入内存中。
try:
with open(path, 'rb') as f: # 用上下文将文件打开
# 判断Excel文件是否加密,未加密直接pandas读取,加密的就先解密到内存中然后pandas读取。
if not msoffcrypto.olefile.isOleFile(f): # mscoffcrypto有可以判断文件是否加密的功能。
pd_excel = pd.read_excel(f, sheet_name, header=header)
logging.info("{title}文件读取成功".format(title=title))
else:
xlf = msoffcrypto.OfficeFile(f) # 用msoffcrypto打开加密文件,未加密文件用这个打开会报错
xlf.load_key(password=password) # 传入文件的密码
xlf.decrypt(decrypted) # 将文件解密并保存到内存中,定义descrypted为io.BytesIO() ,这是msoffcrypto常用方法。
print('xlf.decrypt(decrypted)',decrypted)
pd_excel = pd.read_excel(decrypted) # 将保存到内存中的文件用pandas打开。
# print(pd_excel)
return pd_excel
# pd_excel = pd.read_excel(decrypted, sheet_name, header=header) # 将保存到内存中的文件用pandas打开。
# 通过pandas读取Excel的内容,指定文件路径名称以及要读取的sheet的名称
# logging.info("{title}文件读取成功".format(title=title))
except Exception as e: # 如果文件打开失败,则将报错信息记录到日志中,并向管理员发送邮件。
error_msg = "Excel文件{title}打开失败,请检查文件路径及权限。".format(title=title)
# logging.critical(error_msg)
# logging.critical(e)
# send_waring_mail(error_msg, title)
return
# pd.set_option("display.max_columns", None) # 将pandas输出设置为显示所有列。在辅助print打印时使用
# 将责任时间的数据格式转换成datetime类型,如此在后期可以参与实践比较
# pd_excel['责任时间'] = pd.to_datetime(pd_excel['责任时间'])
print(pd_excel)
return pd_excel
python pandas msoffcrypto-tool excel
最新推荐文章于 2024-05-21 09:57:52 发布