Python怎么实现将Excel内容插入到Word模版中

免费教程   2024年05月10日 9:35  

这篇文章主要讲解了“Python怎么实现将Excel内容插入到Word模版中”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Python怎么实现将Excel内容插入到Word模版中”吧!

实现需求

我是用的开发环境是

3.6

openpyxl 3.1.1

docx 0.2.4

需求

这个是从公司平台导出的订单详情excel文件

这个是公司验收单模版

我这边需求是把Excel文件中的订单号、下单公司、套餐、数量分别添加到模版的订单编号、甲方、验收测试内容中,简单来说就是通过python脚本,将excel文件的订单号、下单公司、套餐、数量分别替换word文件中的OrderID、Company、Package、Quantity

实现代码

明确需求后直接上代码

importopenpyxlimportdocximportdatetimedefget__data():#打开Excel文件wb=openpyxl.load_workbook('下单明细.xlsx')ws=wb['Sheet1']#获取序列号forcellinws['A']:Number.append(cell.value)#获取订单号forcellinws['C']:OrderID.append(cell.value)#OrderID.pop(0)#获取数量forcellinws['F']:Quantity.append(cell.value)#获取公司名称forcellinws['B']:Company.append(cell.value)#获取订单套餐forcellinws['D']:Package.append(cell.value)#替换word文档内容foriinrange(len(Number)):#打开word文档new_doc=docx.Document('交付验收单.docx')forpinnew_doc.paragraphs:forrinp.runs:#print(r.text)if'OrderID'inr.text:#替换订单号item=OrderID[i]r.font.underline=Truer.text=r.text.replace('OrderID',item)print('OrderID'+'更改为'+str(item))if'Quantity'inr.text:#替换数量item=Quantity[i]r.font.underline=Truer.text=r.text.replace('Quantity',str(item))print('Quantity'+'更改为'+str(item))if'Company'inr.text:#替换公司名称item=Company[i]r.font.underline=Truer.text=r.text.replace('Company',str(item))print('Company'+'更改为'+str(item))if'Package'inr.text:#替换订单套餐item=Package[i]r.font.underline=Truer.text=r.text.replace('Package',str(item))print('Package'+'更改为'+str(item))#替换日期#这里因为可以直接改模版所有注释掉了,需要可开启#if'Yy'inp.text:#p.text=p.text.replace('Yy',str(year))#if'Mm'inp.text:#p.text=p.text.replace('Mm',str(month))#if'Dd'inp.text:#p.text=p.text.replace('Dd',str(day))#保存新文档#文件命名格式:交付验收单-公司名称时间序号.docxnew_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__data()运行效果

终端:

文件夹保存文件:

注意:这里我为了方便以及更直观的看到效果,把Excel文件表头栏也进行替换了,后续如果需要可以使用

OrderID.pop(0)将表头栏参数删掉,再把for循环次数减一即可

for i in range(len(Number) - 1):替换后的word文件:

感谢各位的阅读,以上就是“Python怎么实现将Excel内容插入到Word模版中”的内容了,经过本文的学习后,相信大家对Python怎么实现将Excel内容插入到Word模版中这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是,小编将为大家推送更多相关知识点的文章,欢迎关注!

域名注册
购买VPS主机

您或许对下面这些文章有兴趣:                    本月吐槽辛苦排行榜

看贴要回贴有N种理由!看帖不回贴的后果你懂得的!


评论内容 (*必填):
(Ctrl + Enter提交)   

部落快速搜索栏

各类专题梳理

网站导航栏

X
返回顶部