话不多说,直接看代码;
这是excel原数据:
转换成的效果数据(首行为字典的“键”,其余行对应为对应的“值”):
{'Line': 'HG16A', 'Station': 'AT_Audio', 'GroupName': 'AL5626_FA', 'PN': '%', 'Status': '1MM', 'userid': 167942, 'TransDateTime': 20210309133940}
{'Line': 'HG16A', 'Station': 'AT_Audio', 'GroupName': 'AL5626_FA', 'PN': '%', 'Status': 'A4', 'userid': 167942, 'TransDateTime': 20210309133941}
{'Line': 'HG16A', 'Station': 'AT_Audio', 'GroupName': 'AL5626_FA', 'PN': '%', 'Status': 'RAUD', 'userid': 167942, 'TransDateTime': 20210309133941}
{'Line': 'HG16A', 'Station': 'AT_MMI_Auto', 'GroupName': 'AL5626_FA', 'PN': '%', 'Status': 7, 'userid': 167942, 'TransDateTime': 20210309133941}
path_file_name:文件路径名称:
我的这个参数是:
"C:\Users\Administrator\Desktop\line_data.xlsx"
方法1:
@staticmethod
def read_excel_list(path_file_name): # Return 字典格式数据
excel_data = pd.read_excel(path_file_name)
one_row_keys = excel_data.keys() # 读取出来的首行数据
row_keys = [i for i in one_row_keys] # 首行遍历形成的列表格式
sum_rows = excel_data.index.values # 读取所有行数形成列表
df_list = []
for i in sum_rows: # 遍历所有行号
# loc为按列名索引 iloc 为按位置索引,使用的是 [[行号], [列名]]
row_dict = excel_data.loc[i, row_keys].to_dict() #
df_list.append(row_dict)
return df_list
方法2:
@staticmethod
def read_excel_list_plus(path_file_name): # Return 字典格式数据
excel_data = pd.read_excel(path_file_name)
rows, cols = excel_data.shape # 行数 列数
print(excel_data.columns) # 读取第一行表头,返回的是所有行的表头列表
print(excel_data.columns[2]) # 读取第一行表头,第二列 字段名字
print(excel_data["Line"][0]) # 读取 Line列 第0行
df_list = []
for i in range(0, rows): # 遍历所有行
dict_data = {}
for j in excel_data.columns: # 遍历第一行表头
dict_data[j] = excel_data[j][i] # 形成字典键值对
df_list.append(dict_data) # 添加进字典
return df_list
运行效果如图:
就得到对应的字典格式数据啦