2016-05-30 1013 views
1

請幫助我調整docx中表格的行高度。 以下是我寫的代碼在docx文件中寫入數據的代碼 但我沒有得到解決方案來調整表格的行高。Python:如何調整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') 

回答

0

有這個沒有直接的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 

見代碼讓我知道這樣做可以幫助任何人

+0

它幫助美麗。 – xxyzzy

0

我在簡單的函數調用中包裝了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://stackoverflow.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)