python-doxc table 单元格对齐添加新行

python-doxc table cell align adds a new line

我想右对齐使用 python-docx[= 创建的 Word 文档的 table 单元格内的文本34=]。我按照,但问题是在文本之前的de cell中添加了一个新行,所以垂直对齐被破坏了。

这是没有右对齐设置的代码:

table = document.add_table(rows=1, cols=4)
hdr_cells = table.rows[0].cells

hdr_cells[0].width = Inches(0.1)
hdr_cells[1].width = Inches(10)
hdr_cells[2].width = Inches(1)
hdr_cells[3].width = Inches(1)

for entry in context['invoices']['entries']:
    row_cells = table.add_row().cells
    row_cells[0].text = str(entry['amount'])
    row_cells[1].text = entry['line']
    row_cells[2].text = entry['unit_price_label']
    row_cells[3].text = entry['subtotal']

这是生成的文档:

这是正确对齐设置的代码:

table = document.add_table(rows=1, cols=4)
hdr_cells = table.rows[0].cells

hdr_cells[0].width = Inches(0.1)
hdr_cells[1].width = Inches(10)
hdr_cells[2].width = Inches(1)
hdr_cells[3].width = Inches(1)

for entry in context['invoices']['entries']:
    row_cells = table.add_row().cells
    row_cells[0].text = str(entry['amount'])
    row_cells[1].text = entry['line']
    row_cells[2].add_paragraph(entry['unit_price_label']).alignment = WD_ALIGN_PARAGRAPH.RIGHT
    row_cells[3].add_paragraph(entry['subtotal']).alignment = WD_ALIGN_PARAGRAPH.RIGHT

生成的文档:

当 table 单元格与 python-docx 右对齐时,有什么方法可以避免这个回车 return?

简答:是的,使用

row_cells[0].paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.RIGHT

一个table单元格必须始终包含至少一个段落;这是由 ISO 29500 规范规定的(一旦你足够深入地研究它就有意义)。

根据此要求,新的(空的)单元格包含一个空段落。如果您在空单元格上调用 .add_paragraph(),那么您最终会得到 两个 段落。

所以避免多余段落的秘诀是从使用已有的段落开始。仅当您需要多个段落时才调用 .add_paragraph().

单个现有段落作为 cell.paragraphs[0] 访问,可以像 python-docx

中的任何其他段落一样进行操作