Home > Net >  How to define a function to add cell colour for a table that created by python-docx?
How to define a function to add cell colour for a table that created by python-docx?

Time:05-09

I want to define a function to filling header colour, for now, I am just hard code every object.

Here is the code I used, I tried to define a function to add cell colour. The error msg shown below: enter image description here

from docx import Document
from openpyxl import load_workbook
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from zmq import NULL
document = Document()

k=1
for k in range (1,5):
    table  = document.add_table(rows=2, cols=3)
    table.cell(0,0).text = ('Type')
    table.cell(0,1).text = ('Value')
    table.cell(0,2).text = ('Connections')

    def set_table_header_bg_color(table.rows[row_ix].cell):
        """
        set background shading for Header Rows
        """
        tblCell = cell._tc
        tblCellProperties = tc.get_or_add_tcPr()
        clShading = OxmlElement('w:shd')
        clShading.set(qn('w:fill'), "00519E") #Hex of Dark Blue Shade {R:0x00, G:0x51, B:0x9E}
        tblCellProperties.append(clShading)
        return cell


    for each_row in table.rows :
        for each_cell in each_row.cells:
                set_table_header_bg_color(each_cell)

Could you guys help me to solve this error? I copy this function from https://stackoverflow.com/a/62079054/18540814 but the function seems cannot use in my case......

CodePudding user response:

Some things to note

  1. You need to be careful of indentation; 'def' should not be indented and don't place it in the middle of a section of code.
  2. There is no need to initialise a variable when assigning to a range; k=1 isn't needed the range is assigned on the next line.
  3. No need to return the 'cell' the def is a function to change the shading on a cell, there is nothing to return.

As you have written it you are creating 3 tables with the 'k' range not sure if that is your intent.

from docx import Document
from docx.oxml.shared import qn
from docx.oxml.xmlchemy import OxmlElement


doc_name = 'doc_w_tables.docx'
document = Document()
tables = document.tables


def set_table_header_bg_color(tc):
    """
    set background shading for Header Rows
    """
    tblCellProperties = tc._element.tcPr
    clShading = OxmlElement('w:shd')
    clShading.set(qn('w:fill'), "00519E")  # Hex of Dark Blue Shade {R:0x00, G:0x51, B:0x9E}
    tblCellProperties.append(clShading)


for k in range(0, 3):
    table  = document.add_table(rows=2, cols=3)
    table.cell(0, 0).text = 'Type'
    table.cell(0, 1).text = 'Value'
    table.cell(0, 2).text = 'Connections'

    for j in range(0,3):
        set_table_header_bg_color(table.rows[0].cells[j])

document.save(doc_name)

  • Related