首先需要安装python-docx
本文以一个公司调价通知为例,代码如下:
from docx import Document
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.shared import Pt
from docx.oxml.ns import qn
import time
price = input('请输入今日价格:')
customers_list = ['客户1', '客户2', '客户3', '客户4', '客户5', '客户6', '客户7']
today = time.strftime('%Y{y}%m{m}%d{d}', time.localtime()).format(y='年', m='月', d='日')
for i in customers_list:
document = Document()
document.styles['Normal'].font.name = u'宋体'
document.styles['Normal'].element.rPr.rFonts.set(qn('w:eastAsia') , u'宋体')
p1 = document.add_paragraph()
p1.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
run1 = p1.add_run('关于调整%s产品价格的通告' % (today))
run1.font.name = '微软雅黑'
run1.element.rPr.rFonts.set(qn('w:eastAsia') , u'微软雅黑')
run1.font.size = Pt(21)
run1.font.bold = True
p1.space_after = Pt(6)
p1.space_before = Pt(6)
p2 = document.add_paragraph()
r2 = p2.add_run(i+'您好:')
r2.font.name = '宋体'
r2.element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
r2.font.size = Pt(16)
r2.font.bold = True
p3 = document.add_paragraph()
r3 = p3.add_run(' 由于近期各项成本价格的居高不下,我司已经无法克服成本上涨带来的压力,现决定从%s开始调至%s元,此次调价实属无奈,望广大客户予以理解并支持' % (today,price))
p4 = document.add_paragraph()
p4.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT
r4 = p4.add_run('(联系人:高高高 电话:18888888888 )')
r4.font.name = '宋体'
r4.element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
r4.font.size = Pt(12)
r4.font.bold = True
document.save('%s-调价通知.docx' % i)
执行上述代码可以看到,所有生成了所有客户的调价单文档在目录下