Skip to main content
 首页 » 编程设计

python : How to adjust row height of table in docx

2024年10月17日5jpfss

请帮我调整 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') 

请您参考如下方法:

这个没有直接的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 

让我知道它对任何人都有帮助