数据透视表Excel导出
Python数据分析入门PythonExcel
问题
如何导出格式化的Excel报表?
答题要点
import pandas as pd
from openpyxl import load_workbook
from openpyxl.styles import Font, PatternFill, Alignment
# 准备数据
pivot = df.pivot_table(
values='revenue',
index='city',
columns='product',
aggfunc='sum',
margins=True
)
# 导出Excel
output_file = 'report.xlsx'
pivot.to_excel(output_file, sheet_name='收入报表')
# 格式化
wb = load_workbook(output_file)
ws = wb['收入报表']
# 标题行样式
header_fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')
header_font = Font(color='FFFFFF', bold=True)
for cell in ws[1]:
cell.fill = header_fill
cell.font = header_font
cell.alignment = Alignment(horizontal='center')
# 数值格式
for row in ws.iter_rows(min_row=2, min_col=2):
for cell in row:
if cell.value and isinstance(cell.value, (int, float)):
cell.number_format = '#,##0.00' # 千分位
# 列宽自适应
for col in ws.columns:
max_length = max(len(str(cell.value or '')) for cell in col)
ws.column_dimensions[col[0].column_letter].width = max_length + 2
wb.save(output_file)
# 多Sheet导出
with pd.ExcelWriter('multi_sheet_report.xlsx', engine='openpyxl') as writer:
df1.to_excel(writer, sheet_name='概览', index=False)
df2.to_excel(writer, sheet_name='明细', index=False)
pivot.to_excel(writer, sheet_name='透视表')
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题