python docx tables_Python Docx Table row height

问题

So column width is done using cell width on all cells in one column ike this:

from docx import Document

from docx.shared import Cm

file = /path/to/file/

doc = Document(file)

table = doc.add_table(4,2)

for cell in table.columns[0].cells:

cell.width = Cm(1.85)

however, the row height is done using rows, but I can't remember how I did it last week.

Now I managed to find a way to reference the rows in a table, but can't seem to get back to that way. It is possible to change the height by using the add_row method, but you can't create a table with no rows, so the the top row will always be the default height, which about 1.6cms.

There is a way to access paragraphs without using add_paragraph, does anyone know how to access the rows without using the add_row method because it was that that I used to set row height in a table as a default.

I have tried this but it doesn't work:

row = table.rows

row.height = Cm(0.7)

but although this does not give an error, it also has no effect on the height.

回答1:

table.rows is a collection, in particular a sequence, so you need to access each row separately:

for row in table.rows:

row.height = Cm(0.7)

Also check out row.height_rule for some related behaviors you have access to:

https://python-docx.readthedocs.io/en/latest/api/table.html#row-objects

When you assign to table.rows.height, it just adds a .height instance attribute that does nothing. It's one of the side-effects of a dynamic language like Python that you encounter a mysterious behavior like this. It goes away as you gain more experience though, at least it has for me :)

回答2:

Some additional information:

The answer here is correct, but this will give a minimum row height. Using WD_ROW_HEIGHT_RULE.EXACTLY will fix the cell height to the set row height ignoring the contents of the cell, this can result in cropping of the text in an undesirable way.

para = table.cell(0,0).add_paragrph('some text')

SOLUTION:

add_paragraph actually adds a blank line above the text.

Use the following instead to avoid using add_paragraph:

table.cell(0,0).paragraphs[0].text = 'some text'

or using add_run can make it easier to also work with the text:

run = table.cell(0,0).paragraphs[0].add_run('some text')

run.bold = True

来源:https://stackoverflow.com/questions/53194725/python-docx-table-row-height

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值