最新消息:重新回归WordPress,我要比较认真的开始更新我的博客了。

python-docx批量修改、生成word文件

笔记 hanlei 948浏览

需要把excel表中的字段填到word文件中,每行生成一个word文件。excel文件的操作以前用过openpyxl,这次也直接用openpyxl了。word文件以前没在python里操作过,搜索了一下就用python-docx这个库了。

import openpyxl
import docx

def docx_replace_save(filename,text1,text2,text3,text4,text5):
    doc = docx.Document('file.docx')  # type: Doc
    for paragraph in doc.paragraphs:
        runs = paragraph.runs
        for i, run in enumerate(runs):
            run.text=run.text.replace("11111",text1)
            run.text=run.text.replace("22222",text2)
            run.text=run.text.replace("33333",text3)
            run.text=run.text.replace("44444",text4)
            run.text=run.text.replace("55555",text5)
    doc.save("out/" + filename + ".docx")

book=openpyxl.load_workbook("file.xlsx")
sheetnames=book.sheetnames
for sheet in book:
    num=1
    chejian=""
    while sheet['B' + str(num)].value!=None:
        if sheet['B'+ str(num)].value=='岗位':
            num=num+1
            continue
        if sheet['A'+ str(num)].value!=None:
            chejian=sheet['A'+ str(num)].value
        filename=sheet.title + "_" + chejian +  "_" + str(sheet['B' + str(num)].value) +  "_" + str(int(sheet['c' + str(num)].value)*2) + "份"
        filename=filename.replace('/','')
        docx_replace_save(filename,chejian,str(sheet['B' + str(num)].value),str(sheet['D' + str(num)].value),str(sheet['E' + str(num)].value),str(sheet['F' + str(num)].value))
        print(filename)
        num=num+1

转载请注明:HANLEI'BLOG » python-docx批量修改、生成word文件