Python:如何在 docx 中调整表格的行高
Posted
技术标签:
【中文标题】Python:如何在 docx 中调整表格的行高【英文标题】:Python : How to adjust row height of table in docx 【发布时间】:2016-05-30 19:09:15 【问题描述】:请帮我调整 docx 中表格的行高。 以下是我为在 docx 文件中写入数据而编写的代码 但我没有得到调整表格行高的解决方案。
import docx
from docx import Document
from docx.shared import Inches
document = Document()
document.add_heading('Document Title', 0)
p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True
document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='IntenseQuote')
document.add_paragraph(
'first item in unordered list', style='ListBullet'
)
document.add_paragraph(
'first item in ordered list', style='ListNumber'
)
document.add_picture('monty-truth.png', width=Inches(1.25))
table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for item in recordset:
row_cells = table.add_row().cells
row_cells[0].text = str(item.qty)
row_cells[1].text = str(item.id)
row_cells[2].text = item.desc
document.add_page_break()
document.save('demo.docx')
【问题讨论】:
解决方案现在在这里:***.com/questions/53194725/… 【参考方案1】:这个没有直接的api,但是你可以通过为这个添加直接xml来做到这一点
见下方代码
# these imports can go at the top of the file
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
table = document.add_table(rows=1, cols=3)
for item in recordset:
row = table.add_row() # define row and cells separately
# accessing row xml and setting tr height
tr = row._tr
trPr = tr.get_or_add_trPr()
trHeight = OxmlElement('w:trHeight')
trHeight.set(qn('w:val'), "1000")
trHeight.set(qn('w:hRule'), "atLeast")
trPr.append(trHeight)
row_cells = row.cells
row_cells[0].text = str(item.qty)
row_cells[1].text = str(item.id)
row_cells[2].text = item.desc
告诉我这对任何人都有帮助
【讨论】:
帮助非常好。【参考方案2】:我将 Ishaan Sharma 的答案包装在一个简单的函数调用中。这是另一个密切相关的实用程序:
from docx.oxml.shared import OxmlElement, qn
def set_vert_cell_direction(cell):
# https://github.com/python-openxml/python-docx/issues/55
tc = cell._tc
tcPr = tc.tcPr
textDirection = OxmlElement('w:textDirection')
textDirection.set(qn('w:val'), 'btLr')
tcPr.append(textDirection)
def set_row_height(row):
# https://***.com/questions/37532283/python-how-to-adjust-row-height-of-table-in-docx
tr = row._tr
trPr = tr.get_or_add_trPr()
trHeight = OxmlElement('w:trHeight')
trHeight.set(qn('w:val'), "1000")
trHeight.set(qn('w:hRule'), "atLeast")
trPr.append(trHeight)
【讨论】:
以上是关于Python:如何在 docx 中调整表格的行高的主要内容,如果未能解决你的问题,请参考以下文章