1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| from docx import Document
from docx.oxml.shared import OxmlElement
from docx.oxml.ns import qn
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)
def set_cell_bottom(cell):
"""
<w:tcPr>
<w:tcW w:w="6808" w:type="dxa"/>
<w:vAlign w:val="bottom"/>
</w:tcPr>
"""
tc = cell._tc
tcPr = tc.get_or_add_tcPr()
bouton = OxmlElement('w:tcW')
#bouton.append(OxmlElement('w:w="6808'))
bouton.append(OxmlElement('w:type="dxa"'))
bouton.append(OxmlElement('w:vAlign'))
bouton.append(OxmlElement('w:val="bottom"'))
print(bouton)
return bouton
# create document
doc = Document()
# add grid table
table = doc.add_table(rows=2, cols=2, style="Table Grid")
# access second row's cells
data_row = table.add_row().cells
set_cell_margins(data_row[0], top=100, start=100, bottom=100, end=50)
# add headings
data_row[0].text = "Usman"
data_row[1].text = "76"
table2 = doc.add_table(rows=4, cols=4, )
data_row_2 = table2.add_row().cells
set_cell_margins(data_row_2[0], top=250, start=250, bottom=75, end=75)
data_row_2[0].text = "Alter"
data_row_2[1].text = "Mars"
table3 = doc.add_table(rows=1, cols=1, )
data_row_3 = table3.add_row().cells
set_cell_bottom(data_row_3[0] )
# save to file
doc.save("images-table.docx") |
Partager