日期:2025/04/06 02:01来源:未知 人气:52
大家好,这里是程序员晚枫。
上周B站:程序员晚枫 后台的一位朋读者私信我,想学习一下Python自动化生成数据分析报告。
作为有问必答的编程博主,今天我们来一起学习一下~
reportlab是Python的一个标准库,可以画图、画表格、编辑文字,最后可以输出PDF格式。它的逻辑和编辑一个word文档或者PPT很像。有两种方法:
因为需要产生一份给用户看的报告,里面需要插入图片、表格等,所以采用的是第二种方法。
reportlab输入Python的第三方库,使用前需要先安装,
为了方便大家使用,我已经将这个库集成到Python自动化办公的专用库:pip install python-office
中了,
因此一行命令 就可以完成的安装命令如下
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple python-office -U
from reportlab.pdfbase import pdfmetrics # 注册字体 from reportlab.pdfbase.ttfonts import TTFont # 字体类 from reportlab.platypus import Table, SimpleDocTemplate, Paragraph, Image # 报告内容相关类 from reportlab.lib.pagesizes import letter # 页面的标志尺寸(8.5inch, 11inch) from reportlab.lib.styles import getSampleStyleSheet # 文本样式 from reportlab.lib import colors # 颜色模块 from reportlab.graphics.charts.barcharts import VerticalBarChart # 图表类 from reportlab.graphics.charts.legends import Legend # 图例类 from reportlab.graphics.shapes import Drawing # 绘图工具 from reportlab.lib.units import cm # 单位:cm
提前准备好字体文件, 如果同一个文件需要多种字体可以注册多个
pdfmetrics.registerFont(TTFont('SimSun', 'SimSun.ttf')) 封装不同内容对应的函数 创建一个Graphs类,通过不同的静态方法提供不同的报告内容,包括:标题、普通段落、图片、表格和图表。函数中的相关数据目前绝大多数都是固定值,可以根据情况自行设置成相关参数。
if name == 'main':
content = list()
content.append(Graphs.draw_title('数据分析就业薪资'))
content.append(Graphs.draw_img('资料全集.jpg'))
content.append(Graphs.draw_text('众所周知,大数据分析师岗位是香饽饽,近几年数据分析热席卷了整个互联网行业,与数据分析的相关的岗位招聘、培训数不胜数。很多人前赴后继,想要参与到这波红利当中。那么数据分析师就业前景到底怎么样呢?需要学习Python + 大数据分析,可以添加我:CoderWanFeng'))
content.append(Graphs.draw_title('')) content.append(Graphs.draw_little_title('全网同名:程序员晚枫'))
data = [ ('平台名称', '关注人数', '较上年增长率'), ('公众号', '18.5K', '25%'), ('B站', '25.5K', '14%'), ('微博', '29.3K', '10%') ] content.append(Graphs.draw_table(*data))
content.append(Graphs.draw_title('')) content.append(Graphs.draw_little_title('热门城市的就业情况')) b_data = [(25400, 12900, 20100, 20300, 20300, 17400), (15800, 9700, 12982, 9283, 13900, 7623)] ax_data = ['BeiJing', 'ChengDu', 'ShenZhen', 'ShangHai', 'HangZhou', 'NanJing'] leg_items = [(colors.red, '平均薪资'), (colors.green, '招聘量')] content.append(Graphs.draw_bar(b_data, ax_data, leg_items))
doc = SimpleDocTemplate('report.pdf', pagesize=letter) doc.build(content)
生成报告的结果如下
面试20k的Python工程师,聊了这26个问题,个个都是经典!
绝了!深度解析了1道华为笔试题,学会了12种Python正则写法
3年开发了5个私人项目:自动化办公、网站、机器人、小程序……