from docx import Document
# Importing the necessary functions to set the row height
from docx.shared import Cm
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
# Importing the required functions to set the required shading of a cell
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml
# Importing the required function to align our text inside the cells
from docx.enum.text import WD_ALIGN_PARAGRAPH
Прежде всего нам понадобятся некоторые вспомогательные функции.
Мы создадим функцию, которая объединит 2 ячейки в 1 ячейку:
def merge_two_cells(my_table, row_number, start_from_cell):
a = my_table.rows[row_number].cells[start_from_cell]
A = a.merge(my_table.rows[row_number].cells[start_from_cell+1])
Создание функции для настройкивысота строки
def setRowHeight(row, height):
"""
Sets the height of a table row.
`Row` is a `docx.table._Row` object. `height` is the desired height in EMU.
"""
trHeight = OxmlElement('w:trHeight')
trHeight.set(qn('w:val'), str(height.twips))
trPr = OxmlElement('w:trPr')
trPr.append(trHeight)
row._tr.append(trPr)
Создание документа:
document = Document()
table = document.add_table(rows=3, cols=10, style='Table Grid')
setRowHeight(table.rows[2], Cm(2))
## ...etc
merge_two_cells(table, 0, 0)
merge_two_cells(table, 0, 2)
merge_two_cells(table, 0, 4)
merge_two_cells(table, 0, 6)
merge_two_cells(table, 0, 8)
table.rows[0].cells[0].text = 'A'
table.rows[0].cells[2].text = 'B'
table.rows[0].cells[4].text = 'C'
table.rows[0].cells[6].text = 'D'
table.rows[0].cells[8].text = 'E'
table.rows[1].cells[0].text = 'a.1'
table.rows[1].cells[1].text = 'a.2'
table.rows[1].cells[2].text = 'b.1'
## ...etc
table.rows[2].cells[0].text = '1'
## ...etc
#For the shading check here:
#https://stackoverflow.com/questions/26752856/python-docx-set-table-cell-background-and-text-color/43467445#43467445
shading_elm_1 = parse_xml(r'<w:shd {} w:fill="1F5C8B"/>'.format(nsdecls('w')))
table.rows[0].cells[0]._tc.get_or_add_tcPr().append(shading_elm_1)
shading_elm_2 = parse_xml(r'<w:shd {} w:fill="1F5C8B"/>'.format(nsdecls('w')))
table.rows[1].cells[0]._tc.get_or_add_tcPr().append(shading_elm_2)
shading_elm_3 = parse_xml(r'<w:shd {} w:fill="F7CAAC"/>'.format(nsdecls('w')))
table.rows[0].cells[2]._tc.get_or_add_tcPr().append(shading_elm_3)
## ...etc
table.rows[0].cells[0].paragraphs[0].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
## ...etc
document.save('my_test.docx')