Python-docx,如何在表格中設置單元格寬度?(Python-docx, how to set cell width in tables?)


How to set cell width in tables?, so far I got:

from docx import Document
from docx.shared import Cm, Inches

document = Document()
table = document.add_table(rows=2, cols=2)
table.style = 'TableGrid' #single lines in all cells
table.autofit = False

col = table.columns[0] 
col.width=Inches(0.5)
#col.width=Cm(1.0)
#col.width=360000 #=1cm

document.save('test.docx')

No mater what number or units I set in col.width, its width does not change.

解決方案

Short answer: set cell width individually.

for cell in table_columns[0].cells:
    cell.width = Inches(0.5)

python-docx does what you tell it to do when you set column width. The problem is that Word ignores it. Other clients, like LibreOffice, respect the column width setting.

A .docx file is in XML format (hence the 'x' suffix in the file extension). The XML vocabulary for tables has a place for column width and a place for cell width. Who pays attention to what is a bit vexed when it comes to this detail. The one common denominator is that everyone respects explicit widths set at the individual cell level. It doesn't make a lot of sense to me, but this is what it takes to make it work. It might make sense to have a function in your program that takes care of the details:

def set_col_widths(table):
    widths = (Inches(1), Inches(2), Inches(1.5))
    for row in table.rows:
        for idx, width in enumerate(widths):
            row.cells[idx].width = width

This gets a bit more complicated if your table has merged cells, which could actually be the reason Word ignores column widths; they're ambiguous in certain merged-cell situations.

 

如何在表格中設置單元格寬度?,到目前為止,我得到了:



  from docx import Document 
from docx.shared導入Cm,英寸

document = Document()
table = document.add_table(rows = 2,cols = 2)
table.style ='TableGrid'#所有單元格中的單行
table.autofit = False

col = table.columns [0]
col.width = Inches(0.5)
#col.width = Cm(1.0)
#col.width = 360000#= 1cm

document.save('test.docx')


無論我在col.width中設置的數字或單位如何,其寬度都不會改變。


解決方案

簡短答案:分別設置單元格寬度。



 對於table_columns [0] .cells中的單元格:
cell.width =英寸(0.5)


python- docx 會執行設置列寬時告訴它的操作。問題在於Word會忽略它。其他客戶端(例如LibreOffice)也尊重列寬設置。



A .docx 文件為XML格式(因此文件擴展名中的 x后綴)。表的XML詞匯表有一個列寬位置和一個單元格寬度位置。誰在關注這個細節時有些煩惱。一個共同的標准是,每個人都遵守在單個單元格級別設置的顯式寬度。這對我來說意義不大,但這就是使它起作用的必要條件。在您的程序中有一個照顧細節的函數可能很有意義:



  def set_col_widths(table):
widths =(Inches(1),Inches(2),Inches(1.5))
用於table.rows中的行:
for idx,枚舉中的寬度(widths):
行.cells [idx] .width = width


如果您的表合並了單元格,這會變得更加復雜,這實際上可能是Word忽略列寬的原因;在某些合並單元格情況下它們是不明確的


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM