【问题标题】:python-doxc table cell align adds a new linepython-docx 表格单元格对齐添加新行
【发布时间】:2019-01-18 05:47:07
【问题描述】:

我想右对齐使用 python-docx 创建的 Word 文档的表格单元格内的文本。我关注了this advice,但它的问题是在文本之前的单元格内添加了一个新行,因此垂直对齐被破坏了。

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

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

以及生成的文档:

在使用 python-docx 右对齐表格单元格时,有什么方法可以避免这种回车?

【问题讨论】:

    标签: python python-docx


    【解决方案1】:

    简短回答:是的,使用

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

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

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

    因此,避免多余段落的秘诀是从使用已有段落开始。只有当你需要不止一个段落时,你才调用.add_paragraph()

    单个现有段落以cell.paragraphs[0] 访问,并且可以像python-docx 中的任何其他段落一样操作

    【讨论】:

      猜你喜欢
      • 2022-10-20
      • 1970-01-01
      • 1970-01-01
      • 2022-11-28
      • 2012-02-24
      • 1970-01-01
      • 1970-01-01
      • 2014-04-28
      • 1970-01-01
      相关资源
      最近更新 更多