Reputation: 381
To set a background color for cells in a table I am using the following code:
doc.add_paragraph('')
t1 = doc.add_table(rows=7, cols=2)
t1.style = 'TableGrid'
for row in range(7):
cell = t1.cell(row, 0)
cell._tc.get_or_add_tcPr().append(shading_elm_green)
The only problem is that the result is as follows:
But I want all of the cells to have the background color. Why is this not setting all the cells. Plus when I am creating many tables all the cells are clear and the very last cell of the very last table is only set.
What am I doing wrong? Please I am looking for a solution for many days now!
Upvotes: 5
Views: 6530
Reputation: 11
give an example to those who want to know
from docx import Document
from docx.shared import Inches
from docx.enum.table import WD_ALIGN_VERTICAL
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.enum.style import WD_STYLE
from docx.dml.color import ColorFormat
from docx.enum.dml import MSO_COLOR_TYPE
from docx.enum.text import WD_COLOR_INDEX
from docx.enum.text import WD_COLOR
from docx.shared import Pt
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml
document = Document()
document.add_heading('Document Title', 0)
table = document.add_table(1, 11)
table.style = 'Table Grid'
table.cell(0,1).merge(table.cell(0,4))
table.cell(0,6).merge(table.cell(0,7))
table.cell(0,9).merge(table.cell(0,10))
table.cell(0, 0).paragraphs[0].add_run("Name").bold = True
table.cell(0, 5).paragraphs[0].add_run("Offset").bold = True
table.cell(0, 1).paragraphs[0].add_run("5566")
table.cell(0, 6).paragraphs[0].add_run("never die")
table.cell(0, 9).paragraphs[0].add_run("1")
for i in range(11):
table.cell(0, i).paragraphs[0].alignment = WD_ALIGN_VERTICAL.CENTER
shading_elm = parse_xml(r'<w:shd {} w:fill="D9D9D9"/>'.format(nsdecls('w')))
#shading must create every time
table.cell(0, i)._tc.get_or_add_tcPr().append(shading_elm)
document.add_page_break()
document.save('demo2.docx')
Upvotes: 0
Reputation: 28863
You need to create a new shading_elm_green
element for each cell. Each time you assign it in your current code, you're just moving it from one cell to the next. That's why it ends up at the end.
The lxml
API is a little counterintuitive that way (until you think about how you would do it yourself :). When you assign an existing element as a child of another element, for example, using .append()
, lxml
moves the element to be a child of that other element. If you append it to a different element, it moves it there. The assigned element isn't automatically "cloned" or anything like that. It can only live one place, and that place is where you last "placed" it.
You don't show your element creation code, but whatever it is, insert it at the next to last row and things should work the way you expect.
Upvotes: 4