您的位置:首页 > 编程语言 > Python开发

python-docx批处理文档,table中的文本等格式会改变?

2020-02-17 04:54 357 查看

python-docx批处理文档,table中的文本等格式会改变?

在工作中,我们可能会做一些world文档,使用同一个模板,录入不同的信息,并保存。
而复制粘贴复制粘贴,可能会让精神崩溃
那么让python-docx帮你吧

会遇到的–替换模板中的文本信息

大部分情况下,会有两种,一种是在表格中的,一种是不再表格中的。

需要注意的问题

<1>保留模板中文本格式
问题:在python—docx-table中,替换表格中的文本后,格式也会改变


这不是我们想要的
所以:————


所以要深入到runs之后的text。
同样非表格中的文本的替换也是这个道理

源码

# py_docx_world
# the batch production for py_docx_world

import docx,re,datetime

#打开wold模板
doc = docx.Document('C:\\Users\\admin\\Desktop\\我方公司-XXX2019年6月合同.docx')
#储存表格
tables = doc.tables
table = tables[0]
#打开info.txt采集输入的信息
infotxt = open('C:\\Users\\admin\\Desktop\\info.txt')
#读取里面的内容,并储存在列表中
listinfo = infotxt.readlines()

#处理并储存,在列表中的公司名称,税号,地址电话,银行行号
com_name = re.sub(' ','',listinfo[0]).strip()
duty_num = re.sub(' ','',listinfo[1]).strip()
address = re.sub(' ','',listinfo[2]).strip()
phone_num = re.sub(' ','',listinfo[3]).strip()
bank_name = re.sub(' ','',listinfo[4]).strip()
bank_num = re.sub(' ','',listinfo[5]).strip()

#替换docx中的公司名称,税号,地址电话,银行行号
#在文本行中的
##替换公司名称
tamp_info = doc.paragraphs[1].runs[1].text
tamp_info = re.sub('XXX',com_name,tamp_info)
##替换时间
now_time = datetime.datetime.now()
arr_time = str(now_time.year) + '年'+str(now_time.month)+'月'+str(now_time.day)+'日'
doc.paragraphs[1].runs[1].text = re.sub('2019年6月29号',arr_time,tamp_info)
#在表格中的
table.cell(0,1).paragraphs[0].runs[0].text = com_name
table.cell(0,3).paragraphs[0].runs[0].text = duty_num
table.cell(1,1).paragraphs[0].runs[0].text = address+' ' +phone_num
table.cell(1,3).paragraphs[0].runs[0].text = bank_name+' '+bank_num

#替换商品
for row in range(3,6):
if (row+3) < len(listinfo):
list_tamp = re.split('[,,]',listinfo[row+3])
for column in range(0,4):
table.cell(row,column).paragraphs[0].runs[0].text = list_tamp[column].strip()
else:
for column in range(0,4):
table.cell(row,column).paragraphs[0].runs[0].text = ''
#save doc
doc.save('C:\\Users\\admin\\Desktop\\我方公司-'+str(com_name)+str(now_time.year)+'年'+str(now_time.month)+'月合同.docx')

更换前后

前:———

后:———

信息录入前,做什么呢

我的方法是将它储存在txt中:———

如果有更好的方法,欢迎留言哦!!
源文件在这里:
链接: https://pan.baidu.com/s/1tuFJMIcj59cHgZzZ_96NAA 提取码: 9a8q

  • 点赞
  • 收藏
  • 分享
  • 文章举报
破云显空 发布了1 篇原创文章 · 获赞 0 · 访问量 52 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: