使用python读取Exel两种方法

第一种方法

import pandas as pd
def read_excel_to_dicts(file_path):
    # 读取Excel文件
    df = pd.read_excel(file_path, engine='openpyxl')
    # 将DataFrame的每一行转换为字典列表
    # 假设第一行是列名(header),并且你想要所有的列作为字典的键
    rows_as_dicts = df.to_dict(orient='records')
    return rows_as_dicts

# 使用函数并打印结果
excel_file_path = 'people_data.xlsx'  # 替换为你的Excel文件路径
dicts_from_excel = read_excel_to_dicts(excel_file_path)
print(dicts_from_excel)
for row_dict in dicts_from_excel:
    print(row_dict)

第二种方法
from openpyxl import load_workbook
import os


def read_excel_rows(file_path):
    if os.path.exists(file_path):
        wb = load_workbook(file_path)
        ws = wb.active  # 获取活动工作表

        result = []

        # 获取表头(第一行)
        headers = [cell.value for cell in ws[1]]  # 假设第一行是表头

        # 遍历工作表的每一行(从第二行开始,因为第一行是表头)
        for row in ws.iter_rows(min_row=2, values_only=True):
            row_data = {}
            for cell, header in zip(row, headers):
                row_data[header] = cell  # 假设每个单元格都有值,否则可能是None

            result.append(row_data)
            print("数据行:", row_data)  # 如果你还想在控制台上看到数据
            print()  # 打印空行,使数据更清晰
    else:
        print(f"文件 {file_path} 不存在!")
        result = []

    return result  # 返回包含所有行数据的列表

file_path = 'people_data.xlsx'  # 替换为你的Excel文件路径

# 调用函数,读取Excel文件的每一行,并返回包含所有行数据的列表
rows_with_headers = read_excel_rows(file_path)
print(rows_with_headers)


  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值