解析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
相关推荐
odoo中国13 分钟前
Odoo 19 模块结构概述
开发语言·python·module·odoo·核心组件·py文件按
Jelena1577958579216 分钟前
Java爬虫api接口测试
python
代码N年归来仍是新手村成员1 小时前
【Java转Go】即时通信系统代码分析(一)基础Server 构建
java·开发语言·golang
踩坑记录1 小时前
leetcode hot100 3.无重复字符的最长子串 medium 滑动窗口(双指针)
python·leetcode
Z1Jxxx1 小时前
01序列01序列
开发语言·c++·算法
沐知全栈开发2 小时前
C语言中的强制类型转换
开发语言
关于不上作者榜就原神启动那件事2 小时前
Java中大量数据Excel导入导出的实现方案
java·开发语言·excel
坚定学代码2 小时前
基于观察者模式的ISO C++信号槽实现
开发语言·c++·观察者模式·ai
Wang's Blog2 小时前
Nodejs-HardCore: Buffer操作、Base64编码与zlib压缩实战
开发语言·nodejs
csbysj20202 小时前
C# 集合(Collection)
开发语言