解析Excel表表头

常见的一级表头

表头通常位于Excel文件的第一行,包含了每一列的名称。在Excel文件中,第一行的单元格内容通常定义了每一列的字段名称,这些字段名称就是表头。

python 复制代码
import pandas as pd

# 加载Excel文件
file_path = "Test.xlsx"  # 替换为你的文件路径
df = pd.read_excel(file_path)

# 获取表头
headers = df.columns.tolist()

# 打印表头
print("表头信息如下:")
print(headers)

多级表头

对于多级表头,需要使用pandas的header参数来指定表头所在的行。如果表头分布在多行,可以通过header=[0, 1](假设表头分布在第1行和第2行)来解析。

python 复制代码
import pandas as pd

# 加载Excel文件
file_path = "Test.xlsx"  # 替换为你的文件路径
df = pd.read_excel(file_path, header=[0, 1])  # 假设表头分布在第1行和第2行

# 获取表头
headers = df.columns.tolist()

# 打印表头
print("表头信息如下:")
for header in headers:
    print(header)

根据sheet表进行解析

某些情况下只有获取sheet表

python 复制代码
# 常见表头
def parse_headers_from_sheet(sheet):
    # 获取表头信息
    headers = []
    for col in range(1, sheet.UsedRange.Columns.Count + 1):
        header = sheet.Cells(1, col).Value
        if header:
            headers.append(header)
        else:
            break  # 如果某个单元格为空,则假设表头结束
    return headers

# 多级表头
def parse_multilevel_headers_from_sheet(sheet):
    # 获取第一行表头
    first_row_headers = []
    for col in range(1, sheet.UsedRange.Columns.Count + 1):
        header = sheet.Cells(1, col).Value
        if header:
            first_row_headers.append(header)
        else:
            break  # 如果某个单元格为空,则假设表头结束

    # 获取第二行表头
    second_row_headers = []
    for col in range(1, sheet.UsedRange.Columns.Count + 1):
        header = sheet.Cells(2, col).Value
        if header:
            second_row_headers.append(header)
        else:
            break  # 如果某个单元格为空,则假设表头结束

    # 组合多级表头
    headers = list(zip(first_row_headers, second_row_headers))
    return headers
相关推荐
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽2 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程2 天前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪2 天前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook2 天前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田2 天前
使用 pkgutil 实现动态插件系统
python
前端付豪2 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽3 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战3 天前
Pydantic配置管理最佳实践(一)
python