You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用read_excel读取Excel时遇TypeError:需整数却得到datetime.date

解决pandas读取Excel时的TypeError: an integer is required (got type datetime.date)错误

问题重现

执行以下代码读取目标Excel文件:

import pandas as pd
url="https://www.philadelphiafed.org/-/media/frbp/assets/surveys-and-data/survey-of-professional-forecasters/data-files/files/mean_cpi10_level.xlsx"
df= pd.read_excel(url, index_col=0) 

触发错误栈:

TypeError                                 Traceback (most recent call last)
~\anaconda3\lib\site-packages\openpyxl\descriptors\base.py in _convert(expected_type, value)
     54         try:
---> 55             value = expected_type(value)
     56         except:

TypeError: an integer is required (got type datetime.date)

尝试指定dtype参数或直接用openpyxl加载文件,均出现相同错误。

原因

目标Excel文件内部格式异常:部分单元格被标记为整数类型,但实际存储的是日期值,导致openpyxl在解析时类型转换失败。

解决办法

办法1:用pd.ExcelFile配合data_only=True参数

这是最简便的方法,通过传递data_only=True让openpyxl只读取单元格的实际值,忽略格式标记:

import pandas as pd

url = "https://www.philadelphiafed.org/-/media/frbp/assets/surveys-and-data/survey-of-professional-forecasters/data-files/files/mean_cpi10_level.xlsx"
with pd.ExcelFile(url, engine='openpyxl', data_only=True) as xls:
    df = pd.read_excel(xls, index_col=0)

办法2:先下载文件再用openpyxl读取数据值

如果上述方法不行,可以手动下载文件后再处理:

import requests
import pandas as pd
from openpyxl import load_workbook

# 下载文件到本地
url = "https://www.philadelphiafed.org/-/media/frbp/assets/surveys-and-data/survey-of-professional-forecasters/data-files/files/mean_cpi10_level.xlsx"
response = requests.get(url)
with open("mean_cpi10_level.xlsx", "wb") as f:
    f.write(response.content)

# 加载工作簿时只读取实际数据
wb = load_workbook("mean_cpi10_level.xlsx", data_only=True)
ws = wb.active

# 转换为DataFrame
rows = list(ws.iter_rows(values_only=True))
df = pd.DataFrame(rows[1:], columns=rows[0])
df.set_index(rows[0][0], inplace=True)

办法3:降级xlrd使用旧版引擎(可选)

如果你安装的是xlrd 1.2.0版本(支持xlsx),可以指定engine='xlrd':

import pandas as pd

url="https://www.philadelphiafed.org/-/media/frbp/assets/surveys-and-data/survey-of-professional-forecasters/data-files/files/mean_cpi10_level.xlsx"
df = pd.read_excel(url, index_col=0, engine='xlrd')

注意:xlrd 2.0及以上版本不再支持xlsx文件,此方法仅适用于旧版xlrd。

内容的提问来源于stack exchange,提问作者younggotti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 11:24:56