有数据如下,期望将字典的key写在第一行,相同key的值写在同一列
A1={'case1': 1, 'case2': 2, 'case3': 3, 'case4': 5}
B1={'case1': 'A', 'case2': 'B', 'case3': 'C', 'case4': 'D'}
第一种 以行为单位往excel表格写入数据
import pandas as pd
data = [{'case1': 1, 'case2': 2, 'case3': 3, 'case4': 5},
{'case1': 'PASS', 'case2': 'FAIL', 'case3': 'N/A', 'case4': 'Unknown'}]
df = pd.DataFrame(data)
df.to_excel("output.xlsx")
结果:
格式要求:不要第一列,文字居中
import pandas as pd
import openpyxl
from openpyxl.styles import Border, Side, Alignment
data = [{'case1': 1, 'case2': 2, 'case3': 3, 'case4': 5},
{'case1': 'PASS', 'case2': 'FAIL', 'case3': 'N/A', 'case4': 'Unknown'}]
df = pd.DataFrame(data)
df.to_excel("output.xlsx", index=False)
wb = openpyxl.load_workbook('output.xlsx')
wb_name = wb.sheetnames
sheet = wb[wb_name[0]]
# 创建边框样式
border = Border(left=Side(style='thin'),
right=Side(style='thin'),
top=Side(style='thin'),
bottom=Side(style='thin'))
alignment = Alignment(horizontal='center', vertical='center')
for row in sheet.iter_rows():
for cell in row:
cell.border = border
cell.alignment = alignment
wb.save("output.xlsx")
结果:
第二种,一列为单位往excel表格写入数据
import pandas as pd
data = {'case1': [1, 'PASS'], 'case2': [2, 'FAIL'], 'case3': [3, 'N/A'], 'case4': [4, 'Unknown']}
# 写入Excel表格
with pd.ExcelWriter('data.xlsx') as writer:
start_col = 0
for key, value in data.items():
df = pd.DataFrame({key: value})
df.to_excel(writer, index=False, startcol=start_col)
start_col += 1
结果: