Python docx add_paragraph()插入前导换行符

时间:2015-03-31 22:00:21

标签: python docx python-docx

我可以使用段落对象在表格单元格中选择字体大小,颜色,粗体等。但是,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)

3 个答案:

答案 0 :(得分:5)

我尝试了下面的内容,它对我来说很有用。不确定是否是最佳方法:

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

答案 1 :(得分:1)

The solution that I find is to use text attribute instead of add_paragraph() but than use 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

答案 2 :(得分: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 )