1、PPT中插入1个表格
示例说明:创建一个新的PPT文件,添加2个页面,在第二页上插入一个表格,并填充数据,然后保存(没有关闭PPT)
import win32com.client as win32
from win32com.client import constants
import os
# 打开PPT文件
ppt_app = win32.gencache.EnsureDispatch('PowerPoint.Application')
ppt_app.Visible = 1 # 使 PowerPoint 可见
# 创建一个新的PPT
ppt = ppt_app.Presentations.Add()
# 添加一张新的幻灯片
slide = ppt.Slides.Add(1, 1) # 1 表示幻灯片编号,1 表示布局类型
slide = ppt.Slides.Add(2, 2) # 2 表示幻灯片编号,2 表示布局类型
# 定义表格的行数和列数
rows = 3
cols = 4
# 添加表格
table = slide.Shapes.AddTable(rows, cols, 10, 10, 600, 200).Table
# 填充表格数据
data = [
["Header 1", "Header 2", "Header 3", "Header 4"],
["Row 1, Col 1", "Row 1, Col 2", "Row 1, Col 3", "Row 1, Col 4"],
["Row 2, Col 1", "Row 2, Col 2", "Row 2, Col 3", "Row 2, Col 4"]
]
for row_idx, row in enumerate(data):
for col_idx, cell_data in enumerate(row):
cell = table.Cell(row_idx + 1, col_idx + 1)
cell.Shape.TextFrame.TextRange.Text = cell_data
# 保存演示文稿
curr_path = os.getcwd()# 获取当前路径
ppt.SaveAs("%s\\presentation_with_table.pptx"%curr_path)
运行效果:
插入后的表格效果:在第2页中插入了表格,表格中的文字是左对齐的。
2、修改表格的对齐方式
设置表格中的文字水平居中
for row_idx, row in enumerate(data):
for col_idx, cell_data in enumerate(row):
cell = table.Cell(row_idx + 1, col_idx + 1)
cell.Shape.TextFrame.TextRange.ParagraphFormat.Alignment = constants.ppAlignCenter# 设置居中对齐
水平居中效果:
设置垂直居中:
for row_idx, row in enumerate(data):
for col_idx, cell_data in enumerate(row):
cell = table.Cell(row_idx + 1, col_idx + 1)
cell.Shape.TextFrame.VerticalAnchor = 3
垂直居中效果:
其他垂直方向的调节选项
3、修改表格中的字体
# 设置表格的字体样式
font_name = "Arial" # 字体名称
font_size = 12 # 字体大小
font_color = 0xFF0000 # 字体颜色
for row in table.Rows:
for cell in row.Cells:
cell.Shape.TextFrame.TextRange.Font.Name = font_name
cell.Shape.TextFrame.TextRange.Font.Size = font_size
cell.Shape.TextFrame.TextRange.Font.Color.RGB = font_color
运行效果: