Python實現(xiàn)將Excel內(nèi)容插入到Word模版中
前言
前段時間因為需要處理一大堆驗收單,都是一些簡單的復制粘貼替換工作,于是就想到用python進行處理。接下來進入正題~
實現(xiàn)需求
我是用的開發(fā)環(huán)境是
- python 3.6
- openpyxl 3.1.1
- docx 0.2.4
需求
這個是從公司平臺導出的訂單詳情excel文件
這個是公司驗收單模版
我這邊需求是把Excel文件中的訂單號、下單公司、套餐、數(shù)量分別添加到模版的訂單編號、甲方、驗收測試內(nèi)容中,簡單來說就是通過python腳本,將excel文件的訂單號、下單公司、套餐、數(shù)量分別替換word文件中的OrderID、Company、Package、Quantity
實現(xiàn)代碼
明確需求后直接上代碼
import openpyxl import docx import datetime def get_excel_data(): # 打開Excel文件 wb = openpyxl.load_workbook('下單明細.xlsx') ws = wb['Sheet1'] # 獲取序列號 for cell in ws['A']: Number.append(cell.value) # 獲取訂單號 for cell in ws['C']: OrderID.append(cell.value) # OrderID.pop(0) # 獲取數(shù)量 for cell in ws['F']: Quantity.append(cell.value) # 獲取公司名稱 for cell in ws['B']: Company.append(cell.value) # 獲取訂單套餐 for cell in ws['D']: Package.append(cell.value) # 替換word文檔內(nèi)容 for i in range(len(Number)): # 打開word文檔 new_doc = docx.Document('交付驗收單.docx') for p in new_doc.paragraphs: for r in p.runs: # print(r.text) if 'OrderID' in r.text: # 替換訂單號 item = OrderID[i] r.font.underline = True r.text = r.text.replace('OrderID', item) print('OrderID' + '更改為' + str(item)) if 'Quantity' in r.text: # 替換數(shù)量 item = Quantity[i] r.font.underline = True r.text = r.text.replace('Quantity', str(item)) print('Quantity' + '更改為' + str(item)) if 'Company' in r.text: # 替換公司名稱 item = Company[i] r.font.underline = True r.text = r.text.replace('Company', str(item)) print('Company' + '更改為' + str(item)) if 'Package' in r.text: # 替換訂單套餐 item = Package[i] r.font.underline = True r.text = r.text.replace('Package', str(item)) print('Package' + '更改為' + str(item)) # 替換日期 #這里因為可以直接改模版所有注釋掉了,需要可開啟 # if 'Yy' in p.text: # p.text = p.text.replace('Yy', str(year)) # if 'Mm' in p.text: # p.text = p.text.replace('Mm', str(month)) # if 'Dd' in p.text: # p.text = p.text.replace('Dd', str(day)) # 保存新文檔 #文件命名格式:交付驗收單-公司名稱時間序號.docx new_doc.save('交付驗收單-'+ str(Company[i]) +str(year)+str(month)+str(day)+'-' + str(Number[i]) + '.docx') if __name__ == "__main__": Number = [] OrderID = [] Quantity = [] Company = [] Package = [] now = datetime.datetime.now() year = now.strftime("%Y") month = now.strftime("%m") day = now.strftime("%d") get_excel_data()
運行效果
終端:
文件夾保存文件:
注意:這里我為了方便以及更直觀的看到效果,把Excel文件表頭欄也進行替換了,后續(xù)如果需要可以使用
OrderID.pop(0)將表頭欄參數(shù)刪掉,再把for循環(huán)次數(shù)減一即可
for i in range(len(Number) - 1):替換后的word文件:
到此這篇關(guān)于Python實現(xiàn)將Excel內(nèi)容插入到Word模版中的文章就介紹到這了,更多相關(guān)Python Excel內(nèi)容插入到Word內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python numpy多維數(shù)組實現(xiàn)原理詳解
這篇文章主要介紹了python numpy多維數(shù)組實現(xiàn)原理詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-03-03Python?encode()方法和decode()方法詳解
encode() 方法為字符串類型(str)提供的方法,用于將 str 類型轉(zhuǎn)換成 bytes 類型,這個過程也稱為“編碼”,這篇文章主要介紹了Python?encode()方法和decode()方法,需要的朋友可以參考下2022-12-12