解析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
相关推荐
Wadli3 分钟前
C++语法 | static静态|单例模式
开发语言·c++·单例模式
他们都不看好你,偏偏你最不争气26 分钟前
【iOS】AFNetworking
开发语言·macos·ios·objective-c
站大爷IP26 分钟前
5个技巧写出专业Python代码:从新手到进阶的实用指南
python
Bigemap33 分钟前
BigemapPro快速添加历史影像(Arcgis卫星地图历史地图)
java·开发语言
hrrrrb44 分钟前
【Python】字符串
java·前端·python
进击的_鹏1 小时前
【C++11】initializer_list列表初始化、右值引用和移动语义、可变参数模版等
开发语言·c++
mark-puls1 小时前
C语言打印爱心
c语言·开发语言·算法
西阳未落1 小时前
C语言柔性数组详解与应用
c语言·开发语言·柔性数组
Huhbbjs1 小时前
SQL 核心概念与实践总结
开发语言·数据库·sql
大翻哥哥1 小时前
Python 2025:低代码开发与自动化运维的新纪元
运维·python·低代码