Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python docx add_paragraph() inserts leading newline

I'm able to use a paragraph object to select font size, color, bold, etc. within a table cell. But, add_paragraph() seems to always insert a leading \n into the cell and this messes up the formatting on some tables.

If I just use the cell.text('') method it doesn't insert this newline but then I can't control the text attributes.

Is there a way to eliminate this leading newline?

Here is my function:

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)
like image 412
Jason Byrne Avatar asked Oct 15 '25 18:10

Jason Byrne


1 Answers

I tried the following and it worked out for me. Not sure if is the best approach:

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

like image 171
JorgeMacias Avatar answered Oct 18 '25 06:10

JorgeMacias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!