使用python-docx在表格中将单元格加粗

9
下面的代码片段基本上在新的Word文档中创建一个具有所需行数和列数的表格,即2列和14行。然后相应地将内容添加到行和列中。
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]

我一直在尝试使第一列中的所有内容加粗,但是没有成功。

  #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?

3个回答

9

在扩展@Nikos Tavoularis的答案时,您还可以添加一个辅助函数。例如:

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')

编写更多类似于make_rows_bold的函数可以使使用docx更加愉快。


6
您可以使用以下循环来实现这一点:
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

0

您可以重新编写这两行代码

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

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

我们是否可以在加粗的文本中添加超链接?该超链接应引用文档中的一个段落。 - rain

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接