2015-03-31 223 views
2

我可以使用段落對象在表格單元格中選擇字體大小,顏色,粗體等。但是,add_paragraph()似乎總是將一個前導\ n插入到單元格中,這會弄亂某些表格上的格式。Python docx add_paragraph()插入前導換行符

如果我只是使用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) 

回答

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

,我覺得是用文本屬性,而不是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