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种样式:
觉得对自己有帮助的麻烦点个关注、赞,博主将更新更多技术文章