如何在powerpoint表格单元格中设置文本而不丢失字体格式

问题描述 投票:0回答:3

我正在编写 python 代码来使用 python-pptx 修改现有的 powerpoint 文档。我通常可以通过在运行中设置文本来设置文本,同时保留格式:

shape.text_frame.paragraphs[0].runs[0].text = 'mytext'

但是,在我正在修改的表格中,单元格没有运行。它们有一个段落[0],它包含一个没有信息的字体对象(font.name、font.size 为空)。我不知道表格字体信息存储在哪里,但它必须有一些,因为表格在 powerpoint 中工作。如果我向段落添加一个运行并设置其文本,则文本的大小与我在 powerpoint UI 中手动执行此操作的大小不同。如何在表格单元格中设置文本,同时保留原始表格的字体信息?

# this does not preserve table cell formatting...
table = shape.table
cell = table.rows[0].cells[0]
run = cell.text_frame.paragraphs[0].add_run()
run.text = 'mytext'
python-pptx
3个回答
2
投票

PowerPoint 中的文本格式由样式层次结构控制。

直接应用于运行的格式(例如字体大小或斜体)具有第一优先级。从那里开始,它大致是段落默认、表格样式(在表格内时)、从布局继承(仅占位符)、从主继承(仅占位符)和文档/主题默认。这根据位置略有不同,例如是否在表格内,我还没有找到确切规则的明确说明,但这可能会给您一个想法。

因此,要回答您的问题,您需要了解原始表格中的格式来自何处。

我的猜测是直接应用格式,因为这是最终用户最容易获得的格式。另外,你说你的新运行没有直接应用格式,这意味着它们必须从某个地方继承它们的格式。

在这种情况下,解决方案是发现原始运行中的内容并在新运行中将其设置为相同。或者,您可以将它们全部更改为从主题/演示文稿默认值继承。


0
投票

解决 sape 问题,我找到了这个解决方案(不要问我为什么它有效,但它确实有效,我只是通过试错方法找到了答案):

for shape in slide.shapes:
print(shape.name)
print(shape.shape_type)
if (shape.name == str(2)) and ('TABLE' in str(shape.shape_type)):
    table = shape.table
    cell = table.cell(0, 1)
    text_frame = cell.text_frame
    for paragraph in text_frame.paragraphs:
        for run in paragraph.runs:
            run.text = run.text = 'test'

0
投票

这样就解决了问题

if shape.shape_type == 19:  # 19 is the shape type for tables
print("FOUND A TABLE")
# Loop through all the cells in the table
for row in shape.table.rows:
    for cell in row.cells:
        # Store the font and font size of the cell
        font = cell.text_frame.paragraphs[0].runs[0].font
        old_font_name = font.name
        old_font_size = font.size
        # Replace the text in the cell
        cell.text = cell.text.replace('<METRIC1>', 'new_keyword_1')  # replace 'old_keyword' and 'new_keyword' with your keywords
        cell.text = cell.text.replace('<METRIC2>', 'new_keyword_2')  # replace 'old_keyword' and 'new_keyword' with your keywords
        cell.text = cell.text.replace('<METRIC3>', 'new_keyword_3')  # replace 'old_keyword' and 'new_keyword' with your keywords
        # Restore the font and font size of the cell
        font = cell.text_frame.paragraphs[0].runs[0].font
        font.name = old_font_name
        font.size = old_font_size
© www.soinside.com 2019 - 2024. All rights reserved.