如何使用python在表中设置多个独立段落

2024-03-29 08:30:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我无法在表格中设置多缩进段落

我的代码:

import docx

from docx.shared import Cm, Pt

from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_ALIGN_VERTICAL

document = docx.Document()
table = document.add_table(rows = 1, cols = 3, style = 'Table Grid')

# Create row_0
table_rows1 = table.rows[0]
first_merge = table_rows1.cells[0].merge(table_rows1.cells[1])
second_merge = first_merge.merge(table_rows1.cells[2])
table_cell1 = table.rows[0].cells[0]
paragraph = table_cell1.paragraphs[0]
title = paragraph.add_run("TITLE").bold = True
table_cell1.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
table_cell1.vertical_alignment = WD_ALIGN_VERTICAL.CENTER

# Create row_1
add_rows = table.add_row().cells

table_cell2 = table.rows[1].cells[0]
paragraph2 = table_cell2.paragraphs[0]
data2 = paragraph2.add_run(f"\n Lorem")
table.cell(1, 0).width = Cm(5)
table_cell2.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.JUSTIFY

table_cell3 = table.rows[1].cells[1]
paragraph3 = table_cell3.paragraphs[0]
data3 = paragraph3.add_run('\n:')
table.cell(1, 1).width = Cm(0)
table_cell2.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.JUSTIFY

table_cell4 = table.rows[1].cells[2]
paragraph4 = table_cell4.paragraphs[0]
paragraph5 = table_cell4.paragraphs[0]
paragraph6 = table_cell4.paragraphs[0]

data4 = paragraph4.add_run("Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum\n")
data5 = paragraph5.add_run("\n1. Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum\n")
data6 = paragraph6.add_run("\n       a. Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum")
table_cell4.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.JUSTIFY

paragraph5.paragraph_format.left_indent = Cm(0.5)
paragraph5.paragraph_format.first_line_indent = Cm(-0.9)

table.cell(1, 2).width = Cm(40)

document.save('asdfasdf.doc')

结果:

image1

尽管我只更改了data5上的缩进,但为什么所有内容都更改了呢?然而,如果我在没有表格的段落中这样做,这是可行的

我想要的结果是:

image2

那么python-docx能处理这个问题吗?或者oxml能处理这个问题吗?如果可能的话,你能给我一个我可以试试的代码吗?我真的不能用oxml编码

谢谢大家!