解析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
相关推荐
QQ_7781329746 分钟前
从文本到视频:基于扩散模型的AI生成系统全解析(附PyTorch实现)
人工智能·pytorch·python
Cao12345678932111 分钟前
扫雷-C语言版
c语言·开发语言
天堂的恶魔94622 分钟前
QT —— 信号和槽(槽函数)
开发语言·qt
明月看潮生26 分钟前
青少年编程与数学 02-016 Python数据结构与算法 25课题、量子算法
python·算法·青少年编程·量子计算·编程与数学
水w28 分钟前
【Python爬虫】详细入门指南
开发语言·爬虫·python·scrapy·beautifulsoup
weixin_4450547233 分钟前
力扣刷题-热题100题-第35题(c++、python)
c++·python·leetcode
Susea&1 小时前
数据结构初阶:双向链表
c语言·开发语言·数据结构
_x_w2 小时前
【17】数据结构之图及图的存储篇章
数据结构·python·算法·链表·排序算法·图论
pianmian12 小时前
arcgis几何与游标(1)
开发语言·python
-曾牛2 小时前
【LangChain4j快速入门】5分钟用Java玩转GPT-4o-mini,Spring Boot整合实战!| 附源码
java·开发语言·人工智能·spring boot·ai·chatgpt