用python将新建的df按两列分组,两个列名分别为表名和sheeet名,把分组后的df按顺序输出到已有excel中的倒数第二个sheet,表头填充为浅蓝色,全表加边框,居中,i注意:不用load_workbook
时间: 2024-05-11 09:16:38 浏览: 83
好的,可以为您提供相应的代码。请您确认您已经安装了pandas和openpyxl库。
``` python
import pandas as pd
from openpyxl.styles import PatternFill, Border, Side, Alignment
from openpyxl.utils.dataframe import dataframe_to_rows
# 读入已有excel
book = openpyxl.load_workbook('your_excel.xlsx')
# 新建数据表
df = pd.DataFrame({'TableName': ['table1', 'table2', 'table1', 'table3'], 'SheetName': ['sheet1', 'sheet2', 'sheet2', 'sheet1']})
# 按照两列分组
grouped = df.groupby(['TableName', 'SheetName'])
# 将结果逐行写入新的excel sheet,包括表头
sheet = book.create_sheet("NewSheet", -1)
fill = PatternFill(start_color='B9D2EB', end_color='B9D2EB', fill_type='solid')
border = Border(left=Side(border_style='thin', color='000000'), right=Side(border_style='thin', color='000000'), top=Side(border_style='thin', color='000000'), bottom=Side(border_style='thin', color='000000'))
header_style = Alignment(horizontal='center', vertical='center', wrap_text=True)
for name, group in grouped:
sheet.append([name[0], name[1]])
# 将group逐行写入excel
for r in dataframe_to_rows(group, index=False, header=False):
sheet.append(r)
# 添加表头格式和边框
sheet.cell(sheet.max_row-len(group), 1).fill = fill
sheet.cell(sheet.max_row-len(group), 2).fill = fill
sheet['A'+str(sheet.max_row-len(group))].border = border
sheet['B'+str(sheet.max_row-len(group))].border = border
for cell in sheet[sheet.max_row-len(group)+1:sheet.max_row][0]:
cell.border = border
# 居中
cell.alignment = header_style
# 保存excel
book.save('your_excel.xlsx')
```
执行以上代码后,您会得到一个新的名为"NewSheet"的sheet,该sheet包含了按照"TableName"和"SheetName"分组后的df,并按顺序写入已有excel的倒数第二个sheet。表头填充为浅蓝色,全表加边框,居中。
阅读全文