在循环中格式化 运行 并插入 table Python docx

formatting a run within a loop and inserting in a table Python docx

我正在尝试使用 python docx 格式化文本。文本是由循环拉出的字符串。如何将对象命名为 运行,然后将字体应用到 运行?

这是我的代码:

xcount = 0
while xcount < xnum:
    xdata = datastring[xcount]
    obj1 = xdata[0]
    run = obj1
    font = run.font
    from docx.shared import Pt
    font.name = 'Times New Roman'
    row1.cells[0].add_paragraph(obj1)
    xcount += 1

我收到错误:

AttributeError: 'str' object has no attribute 'font'

xdata[0] 是一个字符串(没有 .font 属性)。您需要创建一个 Document(),添加一个段落,然后添加一个 运行。例如:

from docx import Document
from docx.shared import Inches

document = Document()

document.add_heading('Document Title', 0)

p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True

(直接从文档中复制:http://python-docx.readthedocs.io/en/latest/

创建 Table :

from docx import Document
from docx.shared import Inches

document = Document()

document.add_heading('Document Title', 0)


#Adding table 
table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for item in recordset:
    row_cells = table.add_row().cells
    row_cells[0].text = str(item.qty)
    row_cells[1].text = str(item.id)
    row_cells[2].text = item.desc

document.add_page_break()

阅读:python-docx

然后设置这些表格的样式:

#Table styling :
for row in table.rows:
    for cell in row.cells:
        for paragraph in cell.paragraph:
            paragraph.style = 'CellText' # assuming style named "Cell Text"

阅读:apply a paragraph style to each of the paragraphs in each table cell