Search code examples
pythonpython-3.xdocxpython-docx

Writing into table in Word doc using python docx


I'm trying to write into tables in a word template my company uses for statement of works,
I already have working code that takes our template file and saves it as a new filename in a different location. The filepath+filename is new_SOWdst_file_name.

This keeps crashing usually for a failure error about this being not writeable.

Pretty new to python. Any advice appreciated.

# doc = Document(new_SOWdst_file_name)
# f = open(new_SOWdst_file_name, 'r')
# doc = Document(f)


# if customType == ca :
#     sys.exit()
    

# elif customType == sc :
#     SOWNum = doc.tables[0].cell(4,2).text
#     SOWAuthor = doc.tables[0].cell(6,2).text
#     SOWDescriptor = doc.tables[0].cell(8,2).text
#     SOWPartNum = doc.tables[0].cell(9,2).text
#     SOWDate = doc.tables[0].cell(13,1).text
    
#     SOWNum = 'SOW-'+ PartNum
#     SOWAuthor = 'Cody Nelson'
#     SOWDescriptor = Description
#     SOWPartNum = PartNum
#     SOWDate = now.strftime("%b %d, %Y")
    # doc.save(f)
    # f.close()
    # doc.close()
#     sys.exit()
    
# elif customType == cc :
#     sys.exit()
        

Solution

  • doc = Document(new_SOWdst_file_name)
    
    
    doc.tables[0].cell(13,1).text = now.strftime("%b %d, %Y")
    doc.tables[0].cell(9,2).text = PartNum
    doc.tables[0].cell(8,2).text = Description
    doc.tables[0].cell(6,2).text = 'Cody Nelson'
    doc.tables[0].cell(4,2).text = 'SOW-'+ PartNum
    
    doc.save(new_SOWdst_file_name)
    

    Not sure why this works and the other doesn't. But, it works.