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
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- Python中中文输出显示以及列表初始化坑坑
- 千里之行始于足下,看完本文现在开始学Python也来得及
- Python批量处理图片名
- python第一次学习笔记(可能会有更新)
- 使用Python进行数据挖掘的编程问题杂锦
- Python进行数据挖掘常用matplotlib代码片段技巧(持续更新ing..)
- 将python程序打包为exe及一些问题
- 解决安装tensorflow-gpu失败:Command "python setup.py egg_info"failed with error code 10 in........
- python_opencv例程遇到empty() in function 'cv::CascadeClassifier::detectMultiScale'解决办法
- 科学计算和可视化(numpy及matplotlib学习笔记)
- python--验证码
- No module named 'XXX'----python导入模块报此错误的处理方法
- 了解python
- python爬虫URL分析
- 解决Python print 输出文本显示 gbk 编码错误问题
- 基于python3.6的OpenCV如何调用电脑摄像头以及如何播放指定路径下的视频文件
- 基于python3.6的利用OpenCV对数据的写入
- “Python学习”以及“人工智能开发”常用单词总结
- 用python试着简单爬取下360图片的图片
- python简单应用urllib2