python-docx unable to create a table with desired dimensions

30 Views Asked by At
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')

I have write this code which creates a Word file. All the document has only one table with four columns and 10 rows in each page. The problem is that the columns has not the right width to fill the page, and the rows has not the right height to fill the page.

Print screen:

enter image description here

As for the columns I found I manual solution.

enter image description here

but I don't know how to apply it in python-docx. (I am searching something like: https://reference.aspose.com/words/python-net/aspose.words.tables/autofitbehavior/)

0

There are 0 best solutions below