9

The code snippet below basically creates a table with the required number of rows and columns in a new word document i.e 2 columns and 14 rows. It then adds the content to the rows and columns accordingly.

from docx import Document
newDoc=Document()
newDoc.add_heading ('GIS Request Form')
newDoc.add_paragraph()

#inserting a table and the header and value objects to the table
 table=newDoc.add_table(rows=14,cols=2)
 table.style='Table Grid'
 table.autofit=False
 table.columns[0].width=2500000
 table.columns[1].width=3500000

 #inserting contents into table cells
 for i in range(0,14):
   row=table.rows[i]
   row.cells[0].text=reqdheaderList[i]
   row.cells[1].text=reqdvalueList[i]

I have been trying to make the contents of everything in column 1 bold, but it is not working.

  #inserting contents into table cells
   for i in range(0,14):
     row=table.rows[i]
     row.cells[0].text=reqdheaderList[i]
     row.cells[0].paragraphs[0].add_run(line[0]).bold=True
     row.cells[1].text=reqdvalueList[i]

Help?

Nikos Tavoularis
  • 2,843
  • 1
  • 30
  • 27
tg110
  • 401
  • 1
  • 3
  • 15

3 Answers3

9

Expanding @Nikos Tavoularis answer; you can also add a helper function. E.g.:

from docx import Document

def make_rows_bold(*rows):
    for row in rows:
        for cell in row.cells:
            for paragraph in cell.paragraphs:
                for run in paragraph.runs:
                    run.font.bold = True

doc = Document()

table = doc.add_table(rows=4, cols=2)
table.cell(0, 0).text = "Some text"
table.cell(1, 0).text = "Some bold text"
table.cell(1, 1).text = "Some more bold text"
table.cell(2, 0).text = "Some text"
table.cell(3, 1).text = "And more bold text"

make_rows_bold(table.rows[1], table.rows[3])

doc.save('test.docx')

Writing more functions like make_rows_bold can make working with docx way more pleasant.

pmav99
  • 1,909
  • 2
  • 20
  • 27
6

You can achieve that using the following loop:

bolding_columns = [0]
for row in list(range(14)):
    for column in bolding_columns:
        table.rows[row].cells[column].paragraphs[0].runs[0].font.bold = True
pmav99
  • 1,909
  • 2
  • 20
  • 27
Nikos Tavoularis
  • 2,843
  • 1
  • 30
  • 27
0

You may re-write these two lines

     row.cells[0].text=reqdheaderList[i]
     row.cells[0].paragraphs[0].add_run(line[0]).bold=True

to

     row.cells[0].paragraphs[0].add_run(reqdheaderList[i]).bold=True
George
  • 91
  • 1
  • 3
  • Can we also add a hyperlink to the text which is bold? The hyperlink should reference to a paragraph within the document. – rain Apr 01 '21 at 17:56