python-docx 无法创建具有所需维度的表

python-docx unable to create a table with desired dimensions

提问人:Chris P 提问时间:9/27/2023 最后编辑:Chris P 更新时间:9/27/2023 访问量:19

问:

import os
import sys

from docx import Document
from docx.shared import Inches,Cm,Pt
from docx.oxml.shared import OxmlElement # Necessary Import
from docx.oxml.shared import qn
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Pt
from docx.text.run import *

import math

def set_cell_margins(cell, **kwargs):
    """
    cell:  actual cell instance you want to modify

    usage:

        set_cell_margins(cell, top=50, start=50, bottom=50, end=50)

    provided values are in twentieths of a point (1/1440 of an inch).
    read more here: http://officeopenxml.com/WPtableCellMargins.php
    """
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()
    tcMar = OxmlElement('w:tcMar')

    for m in [
        "top",
        "start",
        "bottom",
        "end",
    ]:
        if m in kwargs:
            node = OxmlElement("w:{}".format(m))
            node.set(qn('w:w'), str(kwargs.get(m)))
            node.set(qn('w:type'), 'dxa')
            tcMar.append(node)

    tcPr.append(tcMar)



entries = [i for i in range(0,100)]
    
document = Document()
section = document.sections[-1]  # last section in document

section.top_margin = Cm(0)
section.bottom_margin = Cm(0)
section.left_margin = Cm(0)
section.right_margin = Cm(0)

total_cols = 4
total_rows = math.ceil(len(entries)/4)
table = document.add_table(rows=total_rows, cols=total_cols)
table.style = 'Table Grid'

A4_width_mm = 210
A4_height_mm = 297
cell_width_cm = (A4_width_mm/4)*0.1
cell_height_cm = (A4_height_mm/10)*0.1

for row in table.rows:
    for cell in row.cells:
        cell.width = Cm(cell_width_cm)
        set_cell_margins(cell, top=0,start=0,bottom=0,end=0)
    row.height = Cm(cell_height_cm)


document.save('demo.docx')

我写了这段代码来创建一个 word 文件。所有文档只有一个表格,每页有四列和 10 行。问题在于列的宽度不适合填充页面,行的高度也不适合填充页面。

谁能帮我?

打印屏幕:

enter image description here

至于我找到的列,我手动解决方案。

enter image description here

但我不知道如何在 python-docx 中应用它。(我正在搜索类似的东西:https://reference.aspose.com/words/python-net/aspose.words.tables/autofitbehavior/)

python-docx 尺寸

评论


答: 暂无答案