I'm using docx in python to create tables in a Word document. The code uses an Excel spreadsheet as input and based on the amount of information creates tables for a word document. After the table is generated I need to fill in a subset of cells, but I would like to build this into the code itself.
I found that I can use this code to target specific cells: python docx set table cell background and text color
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml
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)
Unfortunately using this method requires a new element. The number and location of the cells can be defined by the code but I wouldn't know a priori how many cells there would be nor their location. My question therefore is two-fold:
Is there a method that could be used to create new elements using a for loop or other method?
Is there a method for calling these elements?
So for example if my excel input dictates that I will need 100 elements can a write something that creates those elements and then, how would I use a code that can call those (...use shading_elm_1 then shading_elm_2 and so on...)