解析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 小时前
Python快速入门(6)——for/if/while语句
开发语言·经验分享·笔记·python
郝学胜-神的一滴1 小时前
深入解析Python字典的继承关系:从abc模块看设计之美
网络·数据结构·python·程序人生
百锦再2 小时前
Reactive编程入门:Project Reactor 深度指南
前端·javascript·python·react.js·django·前端框架·reactjs
m0_736919103 小时前
C++代码风格检查工具
开发语言·c++·算法
喵手3 小时前
Python爬虫实战:旅游数据采集实战 - 携程&去哪儿酒店机票价格监控完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集结果csv导出·旅游数据采集·携程/去哪儿酒店机票价格监控
2501_944934733 小时前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python
helloworldandy3 小时前
使用Pandas进行数据分析:从数据清洗到可视化
jvm·数据库·python
黎雁·泠崖4 小时前
【魔法森林冒险】5/14 Allen类(三):任务进度与状态管理
java·开发语言
2301_763472465 小时前
C++20概念(Concepts)入门指南
开发语言·c++·算法
肖永威5 小时前
macOS环境安装/卸载python实践笔记
笔记·python·macos