docx center text in table cells

落花浮王杯 提交于 2019-12-01 05:57:31

问题


So I am starting to use pythons docx library. Now, I create a table with multiple rows, and only 2 columns, it looks like this:

Now, I would like the text in those cells to be centered horizontally. How can I do this? I've searched through docx API documentation but I only saw information about aligning paragraphs.


回答1:


There is a code to do this by setting the alignment as you create cells.

doc=Document()
table = doc.add_table(rows=0, columns=2)
row=table.add_row().cells
p=row[0].add_paragraph('left justified text')
p.alignment=WD_ALIGN_PARAGRAPH.LEFT
p=row[1].add_paragraph('right justified text')
p.alignment=WD_ALIGN_PARAGRAPH.RIGHT

code by: bnlawrence

and to align text to the center just change:

p.alignment=WD_ALIGN_PARAGRAPH.CENTER

solution found here: Modify the alignment of cells in a table




回答2:


The most reliable way that I have found for setting he alignment of a table cell (or really any text property) is through styles. Define a style for center-aligned text in your document stub, either programatically or through the Word UI. Then it just becomes a matter of applying the style to your text.

If you create the cell by setting its text property, you can just do

for col in table.columns:
    for cell in col.cells:
        cell.paragraphs[0].style = 'My Center Aligned Style'

If you have more advanced contents, you will have to add another loop to your function:

for col in table.columns:
    for cell in col.cells:
        for par in cell.paragraphs:
            par.style = 'My Center Aligned Style'

You can easily stick this code into a function that will accept a table object and a style name, and format the whole thing.




回答3:


From docx.enum.table import WD_TABLE_ALIGNMENT

table = document.add_table(3, 3)
table.alignment = WD_TABLE_ALIGNMENT.CENTER

For details see a link .

http://python-docx.readthedocs.io/en/latest/api/enum/WdRowAlignment.html



来源:https://stackoverflow.com/questions/42736364/docx-center-text-in-table-cells

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!