python下對word文檔做自動替換(包括頁眉頁腳)


常說的python-docx庫並不好。我使用的時候碰到了部分文字未讀取的情況。其實完全可以不用這個包。

doc文檔本身是一個壓縮包,改后綴為zip后,可解壓看其中的內容:

 

xml格式我不了解,基本上征文所有的文字都在document.xml文檔中,頁眉頁腳在header和footer中,寫一個文檔改變其中的值就行了。

這其中可以用庫來快速操作:zipfile。可以免去解壓什么的繁瑣步驟。

def docx_replace(old_file,new_file,rep):
    zin = zipfile.ZipFile (old_file, 'r')
    zout = zipfile.ZipFile (new_file, 'w')
    for item in zin.infolist():
        buffer = zin.read(item.filename)
        if (item.filename == 'word/document.xml' or 'header' in item.filename):
            res = buffer.decode("utf-8")
            for r in rep:
                res = res.replace(r,rep[r])
            buffer = res.encode("utf-8")
        zout.writestr(item, buffer)
    zout.close()
    zin.close()

做替換,rep是替換前后內容的dict。

so easy

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM