python pptx 表格 图表样式详解

1 篇文章 0 订阅
from pptx import Presentation
slide = prs.slides.add_slide(prs.slide_layouts[6])

表格

单元格合并:

table = slide.shapes.add_table(rows, cols, left, top, width, height).table  # 添加表格,并取表格类
rows = table.rows
row = rows[0]	# 0:开始单元格x坐标
cells = row.cells	
cell = cells[0]	# 0:开始单元格y坐标
other_cell = table.cell(x, y)	# x:结束单元格x坐标	y:结束单元格y坐标
cell.merge(other_cell)

设置单元格宽度

from pptx.util import Cm
table.columns[0].width = Cm(3.5)

设置单元格高度

table.rows[0].height = Cm(1.02)

表格内文本样式

 other_cell = table.cell(x, y)	# x,y 需调整样式的单元格坐标
 para = other_cell.text_frame.add_paragraph()
 para.text = text
 para.font.size = Pt(16)	# 字体大小
 para.font.name = '微软雅黑'
 para.alignment = PP_ALIGN.CENTER	# 对齐,此处为居中
 para.font.bold = Ture	# 字体加粗
 para.font.color.rgb = RGBColor(255, 0, 0)	# 字体颜色

单元格背景填充

cell = table.cell(x, y)
cell.fill.solid()
cell.fill.fore_color.rgb = RGBColor(255, 255, 255)

图表

饼图

from pptx.chart.data import ChartData
from pptx.enum.chart import XL_CHART_TYPE, XL_LABEL_POSITION
from pptx.util import Inches, Pt
from pptx import Presentation
from pptx.dml.color import RGBColor

prs = Presentation()
# 饼图
slide = prs.slides.add_slide(prs.slide_layouts[6])
chart_data = ChartData()
chart_data.categories = ['新闻', '论坛', '微博']
chart_data.add_series(name='负面数', values=[68, 25, 144])
left, top, width, height = Inches(9.5), Inches(2), Inches(15), Inches(15)
graphic_frame = slide.shapes.add_chart(chart_type=XL_CHART_TYPE.PIE,  # 图表类型
                                 x=left, y=top,  # 图表区的位置
                                 cx=width, cy=height,  # 图表的宽和高
                                 chart_data=chart_data)

chart = graphic_frame.chart
chart.chart_style = 10	# 图表样式 有1-48种 下方将列出这48种样式
plot = chart.plots[0]
# 设置数据标签
plot.has_data_labels = True  # 显示数据标签
data_labels = plot.data_labels  # 获取数据标签控制类
data_labels.show_category_name = True  # 是否显示类别名称
data_labels.show_value = True  # 是否显示值
data_labels.show_percentage = True  # 是否显示百分比
data_labels.number_format = '0.0%'  # 标签的数字格式
data_labels.position = XL_LABEL_POSITION.INSIDE_END  # 标签位置
chart.font.name = '微软雅黑'
chart.font.size = Pt(10)
chart.font.bold = True
chart.font.color.rgb = RGBColor(255, 255, 255)
# 标题
chart.has_title = True
chart.chart_title.text_frame.clear()
new_title = chart.chart_title.text_frame.add_paragraph()
new_title.text = '各产业平台负面数量、占比'
new_title.font.size = Pt(18)
new_title.font.color.rgb = RGBColor(0, 0, 0)

prs.save('text.pptx')

结果:
在这里插入图片描述

pptx饼图48种样式:

在这里插入图片描述

觉得对自己有帮助的麻烦点个关注、赞,博主将更新更多技术文章

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值