在 Python 生成的 PPTX 中的 table 中的每一行添加底线

Adding a bottom line to each row in a table in a PPTX generated by Python

我有一个 table,它是使用 pptx 模块 python-pptx 生成并放置在 PPT 文件中的。我想在我的 PPT 文件中 table 的每一行之间添加一行。

我当前的代码:

prs = Presentation('existing-presentation.pptx')
slide = prs.slides.add_slide(prs.slide_layouts[0])
title = slide.shapes.title
title.text = "Slide Title"
df_to_table(slide, df)
prs.save(output)

def df_to_table(slide, df, colnames=None):

    rows, cols = df.shape
    placeholder = slide.placeholders[10]
    res = placeholder.insert_table(rows+1, cols)    
    res.table.columns[0].width = Pt(50)


    if colnames is None:
        colnames = list(df.columns)

    # Insert the column names
    for col_index, col_name in enumerate(colnames):
        # Column names can be tuples
        if not isinstance(col_name, str):
            col_name = " ".join(col_name)
        res.table.cell(0, col_index).text = col_name
        res.table.cell(0, col_index).text_frame.paragraphs[0].font.size=Pt(8)
        res.table.cell(0, col_index).text_frame.paragraphs[0].font.name='Arial'
        res.table.cell(0, col_index).text_frame.paragraphs[0].font.color.rgb=RGBColor(0, 0, 0)
        res.table.cell(0, col_index).fill.solid()
        res.table.cell(0, col_index).fill.fore_color.rgb=RGBColor(255, 255, 255)

    m = df.as_matrix()

    for row in range(rows):
        for col in range(cols):
            val = m[row, col]
            text = str(val)
            res.table.cell(row + 1, col).text = text
            res.table.cell(row + 1, col).text_frame.paragraphs[0].font.size=Pt(8)
            res.table.cell(row + 1, col).text_frame.paragraphs[0].font.name='Arial'
            res.table.cell(row + 1, col).text_frame.paragraphs[0].font.color.rgb=RGBColor(0, 0, 0)
            res.table.cell(row + 1, col).fill.solid()
            res.table.cell(row + 1, col).fill.fore_color.rgb=RGBColor(255, 255, 255) 
            res.table.rows[row+1].height = Pt(0.5)

            if col == 0: #ignore first col with names
                continue
            else:
                res.table.columns[col].width = Pt(55)

不直接符合您的问题,但也许您需要...

查看 Table 的 API,您可以使用 Table 对象的 horz_banding 属性对行进行交替着色。尝试添加您的函数(应用程序第 5 行,if 语句之前)

res.table.horz_banding=true

pptx.shapes.table._Cell 对象(例如从 table.cell(n, m) 接收到的对象)包含 .fill 属性,但不幸的是还没有 .borders 属性。我相信这会在适当的时候到来,但现在还没有。

同时,您需要深入了解 _Cell 下的 lxml 层。

首先,您可以像这样打印单元格元素的 XML:

tc = cell._tc
print tc.xml

您可以创建一个非常小的文档,其中包含带有您想要的边框的 table,然后使用它来检查它。然后您可以使用 lxml 调用添加所需的元素。如果您使用 "python-pptx workaround function" 进行搜索,您会发现一些其他人做过类似事情的例子。