臨時需要完成這樣一個功能,從excel讀取內容生成標准word文檔 考慮用python腳本快速完成 首先需要從excel讀取內容 其次寫入word模板,生成不同的word文件 最后合並所有生成的word文件 excel的每行格式如下: 測試公司 測試地址 測試人員姓名 測試1 測試號 2021/7/22 需要每行對應生成一個word文件,然后將所有的word文件合並到同一個word文件 我們首先手工創建一個word的模板文件dotx,只需要將正常word文件保存成 Word模板(*.dotx) 類型 然后在指定位置插入書簽,用不同的名字來命名書簽,后面插入數據的時候需要。 下面是具體的python腳本了,注意需要安裝os所在的模塊才能執行 python大致如下,內容部分做了替換和簡單說明 from win32com.client import Dispatch from datetime import datetime import os print("讀取創建開始!!") zpath="F:\\dir1\\dir2\\"; print(zpath) mergepath="F:\\dir1\\dir2\\merge\\"; if not os.path.exists(mergepath): 無目錄創建目錄 os.makedirs(mergepath) app = Dispatch('Word.Application') #app.Visible = True xlApp = Dispatch("Excel.Application") #xlApp.Visible = True xlBook = xlApp.Workbooks.Open(zpath+'excel名字.xlsx') 在路徑zpath下的excel文件 for i in range(1): 讀取excel,遍歷每行獲取所需字段的值 print(i) #p1=str(xlBook.Worksheets('sheet1').Cells(i+2, 1).Value) #p1=p1[0:4]+'年' +p1[5:7] + '月' +p1[8:10] +'日' #print(p1) p1=xlBook.Worksheets('sheet1').Cells(i+2, 1).Value print(p1) p2=xlBook.Worksheets('sheet1').Cells(i+2, 2).Value print(p2) p3=xlBook.Worksheets('sheet1').Cells(i+2, 3).Value p3=p3.strip() print(p3) p4=xlBook.Worksheets('sheet1').Cells(i+2, 4).Value p4=p4.strip() print(p4) p5=xlBook.Worksheets('sheet1').Cells(i+2, 5).Value print(p5) p6=str(xlBook.Worksheets('sheet1').Cells(i+2, 6).Value) 時間處理 p6=p6[0:4]+'年' +p6[5:7] + '月' +p6[8:10] +'日' print(p6) doc = app.Documents.Add(zpath+'創建的word模板.dotx') doc.Bookmarks("位置名字1").Range.Text = p1 將excle中每行的字段填寫到模板中的位置 doc.Bookmarks("位置名字2").Range.Text = p2 doc.Bookmarks("位置名字3").Range.Text = p3 doc.Bookmarks("位置名字4").Range.Text = p5 doc.Bookmarks("位置名字5").Range.Text = p4 doc.Bookmarks("位置名字6").Range.Text = p6 doc.Bookmarks("位置名字7").Range.Text = p1 這個位置使用同樣的內容 # doc.Bookmarks("位置6").Range.Text = "{0:%Y}年{0:%m}月{0:%d}日".format(datetime.now()) doc.SaveAs(mergepath+'單個word文檔的名字_'+p4+'.docx') p4是每行中一個區別其他行的特殊標記 doc.Close() #app.Documents.Close() app.Quit() xlBook.Close() xlApp.Quit() print("讀取創建結束!!") print("開始合並!!") word = Dispatch('Word.Application') #word.Visible = False #需要合並的文件所在路徑 files = [] filename = os.listdir(mergepath) filename.sort(key= lambda x:str(x[:-5])) for filename in filename: filename = os.path.join(mergepath,filename) print(filename) files.append(filename) #獲取目錄下所有文件的路徑 output = word.Documents.Add() #新建空的word文檔, for file in files: output.Application.Selection.InsertFile(file) #拼接文檔 doc = output.Range(output.Content.Start, output.Content.End) #獲取合並后文檔的內容 output.SaveAs(mergepath+'merge.docx') #把匯總文件保存到指定路徑 output.Close()#關閉 word.Quit() print("合並結束!!")