数据导出PDF报告
Python数据分析入门Python
问题
如何生成PDF格式的数据分析报告?
答题要点
from fpdf import FPDF
import matplotlib.pyplot as plt
# 生成图表
plt.figure(figsize=(10, 6))
df.plot(x='date', y='dau')
plt.title('DAU Trend')
plt.savefig('chart1.png', dpi=150, bbox_inches='tight')
plt.close()
# 创建PDF
pdf = FPDF()
pdf.add_page()
# 设置字体(中文需要特殊处理)
pdf.set_font('Arial', 'B', 16)
# 标题
pdf.cell(0, 10, 'Monthly Report - Dec 2024', ln=True, align='C')
pdf.ln(10)
# 正文
pdf.set_font('Arial', '', 12)
pdf.multi_cell(0, 10, 'This is the monthly report summary...')
pdf.ln(5)
# 插入图表
pdf.image('chart1.png', x=10, y=pdf.get_y(), w=190)
pdf.ln(100)
# 表格
pdf.set_font('Arial', 'B', 12)
pdf.cell(60, 10, 'Metric', border=1)
pdf.cell(60, 10, 'Value', border=1, ln=True)
pdf.set_font('Arial', '', 12)
metrics = [('DAU', '150,000'), ('Revenue', '$50,000')]
for metric, value in metrics:
pdf.cell(60, 10, metric, border=1)
pdf.cell(60, 10, value, border=1, ln=True)
# 保存
pdf.output('monthly_report.pdf')
# 使用ReportLab(更强大)
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Image
from reportlab.lib.styles import getSampleStyleSheet
doc = SimpleDocTemplate('advanced_report.pdf', pagesize=letter)
story = []
# 添加标题
styles = getSampleStyleSheet()
story.append(Paragraph('Monthly Report', styles['Title']))
# 添加表格
data = [['Metric', 'Value'],
['DAU', '150,000'],
['Revenue', '$50,000']]
table = Table(data)
table.setStyle(TableStyle([
('BACKGROUND', (0,0), (-1,0), '#4472C4'),
('TEXTCOLOR', (0,0), (-1,0), 'white'),
('GRID', (0,0), (-1,-1), 1, 'black')
]))
story.append(table)
# 添加图片
story.append(Image('chart1.png', width=400, height=300))
doc.build(story)
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题