2

我可以使用段落对象在表格单元格中选择字体大小、颜色、粗体等。但是,add_paragraph()似乎总是在单元格中插入一个前导 \n,这会弄乱某些表格的格式。

如果我只使用该cell.text('')方法,它不会插入此换行符,但我无法控制文本属性。

有没有办法消除这个领先的换行符?

这是我的功能:

def add_table_cell(table, row, col, text, fontSize=8, r=0, g=0, b=0, width=-1):
    cell = table.cell(row,col)
    if (width!=-1):
    cell.width = Inches(width)
    para = cell.add_paragraph(style=None)
    para.alignment = WD_ALIGN_PARAGRAPH.LEFT
    run = para.add_run(text)
    run.bold = False
    run.font.size = Pt(fontSize)
    run.font.color.type == MSO_COLOR_TYPE.RGB
    run.font.color.rgb = RGBColor(r, g, b)
4

3 回答 3

6

我尝试了以下方法,它对我有用。不确定是否是最好的方法:

cells[0].text = 'Some text' #Write the text to the cell

#Modify the paragraph alignment, first paragraph cells[0].paragraphs[0].paragraph_format.alignment=WD_ALIGN_PARAGRAPH.CENTER

于 2015-04-25T18:46:32.460 回答
2

我找到的解决方案是使用文本属性而不是 add_paragraph(),而不是使用 add_run():

row_cells[0].text = ''
row_cells[0].paragraphs[0].add_run('Total').bold = True
row_cells[0].paragraphs[0].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.RIGHT
于 2016-04-04T17:46:58.867 回答
0

这对我有用。我不调用 add_paragraph()。我只是在这个调用中引用了第一段 -> para = cell.paragraphs[0]。之后的一切都是通常的 api 调用。

table = doc.add_table( rows=1, cols=3 )   #   bar codes

for tableRow in table.rows:
    for cell in tableRow.cells:
        para = cell.paragraphs[0]
        run = para.add_run( "*" + specIDStr + "*" )
        font = run.font
        font.name = 'Free 3 of 9'
        font.size = Pt( 20 )

        run = para.add_run( "\n" + specIDStr 
            + "\n" + firstName + " " + lastName
            + "\tDOB: " + dob )
        font = run.font
        font.name = 'Arial'
        font.size = Pt( 8 )
于 2020-11-18T18:33:09.010 回答