使用 python docx 在 Word 文档中写入 table

Writing into table in Word doc using python docx

我正在尝试在我公司用于作品说明的 word 模板中写入表格,
我已经有了使用我们的模板文件并将其作为新文件名保存在不同位置的工作代码。文件路径+文件名是new_SOWdst_file_name.

这通常会因为无法写入的失败错误而不断崩溃。

对 python 很陌生。任何建议表示赞赏。

# 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()
        

在读取或写入文件之前不要打开文件。 python-docx 会为您处理所有这些细节。您只需要:

document = Document(new_SOWdst_file_name)
# ... do your work with `document`
document.save("new-file-name.docx")
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)

不确定为什么这个有效而另一个无效。 但是,它有效。