在Python中打开Excel文件:XLRDError: Excel xlsx file; 不支持

nil*_*ore 6 python excel pandas

我想在 Python 中打开 Excel 文件,使用:

import xlrd

loc = (r"C:\Users\my_path\my_file.xlsx")

wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
sheet.cell_value(0, 0)
Run Code Online (Sandbox Code Playgroud)

它捕获了错误:

---------------------------------------------------------------------------
XLRDError                                 Traceback (most recent call last)
<ipython-input-70-b399ced4986e> in <module>
      4 loc = (r"C:\Users\my_path\my_file.xlsx")
      5 
----> 6 wb = xlrd.open_workbook(loc)
      7 sheet = wb.sheet_by_index(0)
      8 sheet.cell_value(0, 0)

C:\Python38\lib\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
Run Code Online (Sandbox Code Playgroud)

怎么了?

小智 15

最新版本的xlrd仅支持.xls文件,因此您可以安装旧版本

pip uninstall xlrd

pip install xlrd==1.2.0
Run Code Online (Sandbox Code Playgroud)


小智 6

或者您可以使用 openpyxl 来完成此操作。

pip install openpyxl
Run Code Online (Sandbox Code Playgroud)

如果你在 Pandas 中使用它:

import pandas as pd
pd.read_excel('file/path/to/excel/spreadsheet.xlsx', engine='openpyxl')
Run Code Online (Sandbox Code Playgroud)

如果您不指定引擎,它将使用默认值。