How to check a checkbox with docx

I’m trying to get a checkbox from a table inside a pre-made word doc but I’m having trouble getting it to function. I came across this SO post that has helped me almost get there, but I’m still unabel to fully understand/get it to work. What I have so far:

import docx
from docx import Document
from docx.oxml import OxmlElement
from docx.oxml.ns import qn


def checkedElement():
    ele = OxmlElement('w:checked')
    ele.set(qn('w:val'), "true")
    return ele

def yesNoCheck(yes_no, tableIdx, coords):
    print(coords, yes_no)
    if yes_no == 'y':
        index = 0
        x = doc.tables[tableIdx].cell(coords[0]),coords[1]._element.xpath('.//w:checkBox')
        x[index].append(checkedElement())
    elif yes_no == 'n':
        index = 1
        x = doc.tables[tableIdx].cell(coords[0]),coords[1]._element.xpath('.//w:checkBox')
        x[index].append(checkedElement())
    else:
        print('Value was neither yes or no')
        pass

table1 = {
    'thisisthetabletocheck':[0,0]
}

def row_as_dicts(data):
    colnames = data[0]
    for row in data[1]:
        yield dict(zip(colnames, row))

fc_data = [
    ['thisisthetabletocheck'],
    ['thisisthetabletocheck']
]

for row in row_as_dicts(fc_data):
    doc = Document("trythis.docx")
    yesNoCheck(row['thisisthetabletocheck'], 0, table1['thisisthetabletocheck'])

    doc.save('this.docx')

The part where I believe I am going wrong is with the fc_data dict, row_as_dicts function and the yes_no variable. I’m not sure what would go in the varaible, seems the way it is labled it coems from an external source that is not a docx file. Originally I believed it was a named table, but I’m not sure if you could name the table. Once those are settled I believe this should work as I’d want it to, I’m not sure if I am missing something or if the code is outdated and is no longer viable.

Leave a Comment