• Pandas读取Excel文件XLRDError: Excel xlsx file; not supported


    问题背景:

            工作中大部使用Pandas分处理的数据都是以csv后缀结尾的文件,但是突然换成xlsx后缀的表格之后,出现的一些错误。

    问题现象:

            XLRDError: Excel xlsx file; not supported

    /usr/local/lib/python3.6/site-packages/xlrd/__init__.py in open_workbook(filename, logfile, verbosity, use_mmap, file_contents, encoding_override, formatting_info, on_demand, ragged_rows, ignore_workbook_corruption)
        168     # files that xlrd can parse don't start with the expected signature.
        169     if file_format and file_format != 'xls':
    --> 170         raise XLRDError(FILE_FORMAT_DESCRIPTIONS[file_format]+'; not supported')
        171 
        172     bk = open_workbook_xls(
    
    XLRDError: Excel xlsx file; not supported
    1. import pandas as pd
    2. PATH = '/tmp/MSD0921.xlsx'
    3. dataframe = pd.read_excel(PATH, engine=None)

    查看源码:

            在pandas的base.py文件的ExcelFile类下边有这么一段描述,大概在1117-1127行。

    engine : str, default None
        If io is not a buffer or path, this must be set to identify io.
        Supported engines: ``xlrd``, ``openpyxl``, ``odf``, ``pyxlsb``
        Engine compatibility :
    
        - ``xlrd`` supports old-style Excel files (.xls).
        - ``openpyxl`` supports newer Excel file formats.
        - ``odf`` supports OpenDocument file formats (.odf, .ods, .odt).
        - ``pyxlsb`` supports Binary Excel files.
    
        .. versionchanged:: 1.2.0
    
           The engine `xlrd `_
           now only supports old-style ``.xls`` files.
           When ``engine=None``, the following logic will be
           used to determine the engine:

    源码解读:

            大概的意思是,pandas 读取excel表格只支持这四种引擎,xlrd,openpyxl,odf,pyxlsb如果不是这四种就会抛出异常。如果engine=None的话,默认的就是xlrd引擎,只支持老式的Excel文件,.xls后缀的

    代码修改:

    只需要将引擎换成 openpyxl即可

    1. import pandas as pd
    2. PATH = '/tmp/MSD0921.xlsx'
    3. dataframe = pd.read_excel(PATH,engine='openpyxl')

     总结:关于第三方库代码的问题,要学去看源码,分析问题所在,大部分问题都能够解决

  • 相关阅读:
    19【迭代器设计模式】
    STC 51单片机57——矩阵键盘 基本原理演示
    Cesium中3DTiles模型平移至指定经纬度
    技术对接51
    使用Robot Framework实现多平台自动化测试
    青少年护眼灯多大功率最合适?分享几款适合青少年的护眼台灯
    10:00面试,10:06就出来了,问题问的实在有点变态
    2024.6.12 作业 xyt
    切比雪夫多项式
    visual studio常用快捷键
  • 原文地址:https://blog.csdn.net/qq_42336581/article/details/128074277