用python将新建的df按两列分组,两个列名分别为表名和sheeet名,把分组后的df按顺序输出到已有excel中的倒数第二个sheet,表头填充为浅蓝色,全表加边框,居中,不用load_workbook
时间: 2024-05-21 07:12:31 浏览: 142
python实现跨excel的工作表sheet之间的复制方法
5星 · 资源好评率100%
import pandas as pd
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Border, Alignment, Side
# 新建一个例子DataFrame
data = {'表名': ['表1', '表2', '表1', '表2'], 'sheet名': ['sheet1', 'sheet1', 'sheet2', 'sheet2'], '数值': [1, 2, 3, 4]}
df = pd.DataFrame(data)
# 分组
grouped = df.groupby(['表名', 'sheet名'])
# 将分组后的df按顺序输出到已有excel中的倒数第二个sheet
book = Workbook()
sheet = book.create_sheet('Sheet1', 0)
for index, (name, group) in enumerate(grouped, start=1):
if index == 1:
output_sheet = book.create_sheet('output', len(book.sheetnames)-1)
output_sheet.append(list(group.columns))
output_sheet.append(list(group.values[0]))
# 表头填充为浅蓝色
header_fill = PatternFill(start_color='ADD8E6', end_color='ADD8E6', fill_type='solid')
for cell in output_sheet[1]:
cell.fill = header_fill
# 全表加边框,居中
border = Border(left=Side(border_style='thin'), right=Side(border_style='thin'),
top=Side(border_style='thin'), bottom=Side(border_style='thin'))
alignment = Alignment(horizontal='center', vertical='center')
for row in output_sheet.iter_rows(min_row=1):
for cell in row:
cell.border = border
cell.alignment = alignment
book.save('output.xlsx')
print('Done')
阅读全文