第一种方法
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)
01-26
1万+
05-23
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交