我正在尝试使用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'
答案 0 :(得分:3)
创建表:
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
答案 1 :(得分:1)
xdata[0]
是一个字符串(没有.font
属性)。您需要创建一个Document()
,添加一个段落,并为其添加一个运行。 E.g:
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
(直接从文档中复制:https://gist.github.com/meddulla/b1ec2d2c47577ee7f549a40ad8c40a88)