python-pptx
是一个用于创建和修改 PowerPoint 文件的 Python 库。你可以使用它来创建和格式化表格。以下是如何使用 python-pptx
库来格式化表格的步骤和示例代码。
python-pptx
首先,你需要安装 python-pptx
库。你可以使用 pip
来安装:
pip install python-pptx
以下是一个完整的示例,展示如何使用 python-pptx
创建和格式化表格。
from pptx import Presentation
from pptx.util import Inches, Pt
from pptx.enum.text import PP_ALIGN
from pptx.dml.color import RGBColor
# 创建一个新的演示文稿
prs = Presentation()
# 添加一个幻灯片
slide_layout = prs.slide_layouts[5] # 使用空白布局
slide = prs.slides.add_slide(slide_layout)
# 定义表格的位置和大小
left = Inches(2.0)
top = Inches(2.0)
width = Inches(6.0)
height = Inches(1.5)
# 添加表格
rows = 3
cols = 4
table = slide.shapes.add_table(rows, cols, left, top, width, height).table
# 设置列宽
for col in range(cols):
table.columns[col].width = Inches(1.5)
# 填充表格数据
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 in range(rows):
for col in range(cols):
cell = table.cell(row, col)
cell.text = data[row][col]
# 设置字体大小和对齐方式
for paragraph in cell.text_frame.paragraphs:
for run in paragraph.runs:
run.font.size = Pt(12)
run.font.bold = True if row == 0 else False # 使表头加粗
run.font.color.rgb = RGBColor(0, 0, 0) # 设置字体颜色为黑色
paragraph.alignment = PP_ALIGN.CENTER # 居中对齐
# 设置单元格背景颜色
if row == 0:
cell.fill.solid()
cell.fill.fore_color.rgb = RGBColor(192, 192, 192) # 灰色背景
# 保存演示文稿
prs.save('formatted_table.pptx')
Presentation()
创建一个新的 PowerPoint 演示文稿对象。slide_layouts[5]
添加一个空白布局的幻灯片。Inches
定义表格的位置和大小。add_table
方法添加一个表格,并指定行数和列数。save
方法保存演示文稿。领取专属 10元无门槛券
手把手带您无忧上云