python pandas msoffcrypto-tool excel

#解决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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值