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

使用pandas.read_excel读取多sheet的xlsx返回空DataFrame(含正确表头)

解决Pandas读取Excel非首工作表返回空DataFrame的问题

以下是几种无需手动干预的可行方案,可根据场景选择:

方案1:用openpyxl直接读取单元格数据

绕过pandas默认读取逻辑,直接用openpyxl遍历单元格并筛选有效数据,适合跨平台场景:

from openpyxl import load_workbook
import pandas as pd
import os

file_path = os.path.join(path, input_file)
wb = load_workbook(file_path, read_only=True)
ws = wb['sheet_name']

# 提取表头
headers = [cell.value for cell in ws[1]]
# 提取非空数据行
data_rows = []
for row in ws.iter_rows(min_row=2, values_only=True):
    if any(cell is not None and str(cell).strip() != '' for cell in row):
        data_rows.append(row)

# 构建DataFrame
df = pd.DataFrame(data_rows, columns=headers)
wb.close()

方案2:自动模拟Excel另存操作

完全复现手动另存的修复逻辑,依赖Windows系统的Excel客户端,适配所有复杂格式文件:

import win32com.client as win32
import os

file_path = os.path.join(path, input_file)
temp_file = os.path.join(path, f"temp_{input_file}")

# 初始化Excel后台进程
excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.Visible = False
excel.DisplayAlerts = False

# 打开文件并另存为标准xlsx格式
wb = excel.Workbooks.Open(file_path)
# 若数据来自外部链接,可先刷新:
# wb.RefreshAll()
# excel.CalculateUntilAsyncQueriesDone()
wb.SaveAs(temp_file, FileFormat=51)
wb.Close()
excel.Quit()

# 读取处理后的文件
df = pd.read_excel(temp_file, sheet_name='sheet_name')

# 清理临时文件(可选)
os.remove(temp_file)

方案3:针对Excel表对象(List Object)的读取

如果目标工作表数据存储在Excel内置表对象中,直接读取表区域:

from openpyxl import load_workbook
import pandas as pd
import os

file_path = os.path.join(path, input_file)
wb = load_workbook(file_path)
ws = wb['sheet_name']

# 获取工作表中的表对象
tables = list(ws.tables.values())
if not tables:
    raise ValueError("目标工作表中未找到表对象")

target_table = tables[0]
# 提取表的单元格数据
table_range = ws[target_table.ref]
table_data = [[cell.value for cell in row] for row in table_range]
df = pd.DataFrame(table_data[1:], columns=table_data[0])
wb.close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 08:05:17