import pandas as pd
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
# 假设你已经有了一个DataFrame
df = pd.DataFrame({
'A': [1, 2, 3],
'B': [4, 5, 6],
'C': [7, 8, 9]
})
# 创建一个Workbook对象
wb = Workbook()
ws = wb.active
ws.title = 'Merged Sheet'
# 将DataFrame写入到worksheet中
for r_idx, row in df.iterrows():
for c_idx, value in enumerate(row, 1):
ws.cell(row=r_idx + 1, column=c_idx, value=value)
# 设置标题行样式
header_row = [ws.cell(row=1, column=col) for col in range(1, len(df.columns) + 1)]
bold_font = Font(bold=True)
blue_fill = PatternFill(start_color='0000FF', end_color='0000FF', fill_type='solid')
alignment = Alignment(wrap_text=True)
for cell in header_row:
cell.font = bold_font
cell.fill = blue_fill
cell.alignment = alignment
# 设置整个DataFrame的框线
thin_border = Border(left=Side(border_style='thin'),
right=Side(border_style='thin'),
top=Side(border_style='thin'),
bottom=Side(border_style='thin'))
# 应用框线到所有单元格
for row in ws.iter_rows():
for cell in row:
cell.border = thin_border
# 保存Excel文件
wb.save('styled_dataframe.xlsx')
04-26
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交