我一直在寻找一种方法来查找和替换docx文件中的文本而运气不佳 . 我已经尝试过docx模块而无法使用它 . 最后,我使用zipfile模块计算了下面描述的方法,并替换了docx存档中的document.xml文件 . 为此,您需要一个模板文档(docx),其中您要替换的文本作为唯一字符串,无法与文档中的任何其他现有或未来文本匹配(例如,“XXXMEETDATEXXX上与XXXCLIENTNAMEXXX的 Session 进行得非常顺利 . “) .
import zipfile
replaceText = {"XXXCLIENTNAMEXXX" : "Joe Bob", "XXXMEETDATEXXX" : "May 31, 2013"}
templateDocx = zipfile.ZipFile("C:/Template.docx")
newDocx = zipfile.ZipFile("C:/NewDocument.docx", "a")
with open(templateDocx.extract("word/document.xml", "C:/")) as tempXmlFile:
tempXmlStr = tempXmlFile.read()
for key in replaceText.keys():
tempXmlStr = tempXmlStr.replace(str(key), str(replaceText.get(key)))
with open("C:/temp.xml", "w+") as tempXmlFile:
tempXmlFile.write(tempXmlStr)