利⽤python向word⽂档模板中写⼊内容第⼀部分:先看成果
Talk is cheap show me the code!(我来翻译⼀哈:不bb上代码)
import os
os.chdir('D:\\python_major\\auto_office14')
import datetime
from docx import Document
um.text import WD_ALIGN_PARAGRAPH
from docx.shared import Pt, RGBColor
l.ns import qn
doc = Document()
heading_1 ='请假条'
paragraph_1 = doc.add_heading(heading_1, level =1)
paragraph_1.alignment = WD_ALIGN_PARAGRAPH.CENTER
greeting_word ='尊敬的领导:'python中文文档
paragraph_2 = doc.add_paragraph(greeting_word)
name =input("请输⼊请假⼈姓名:")
division =input("请输⼊所属部门:")
reason =input("请输⼊请假事由:")
day =input('请输⼊请假天数:')
detailed_time =input("请输⼊请假的具体时间:")
word_1 ="    本⼈"
word_2 =",所在部门"
word_3 =",由于"
word_4 =",需请假"
word_5 ="天,请假的具体时间为"
word_6 ="。"
paragraph_3 = doc.add_paragraph()
paragraph_3.add_run(word_1)
paragraph_3.add_run("{0: ^{1}}".format(name,len(name)+6)).underline =True
paragraph_3.add_run(word_2)
paragraph_3.add_run("{0: ^{1}}".format(division,len(division)+6)).underline =True
paragraph_3.add_run(word_3)
paragraph_3.add_run("{0: ^{1}}".format(reason,len(reason)+6)).underline =True
paragraph_3.add_run(word_4)
paragraph_3.add_run("{0: ^{1}}".format(day,len(day)+6)).underline =True
paragraph_3.add_run(word_5)
paragraph_3.add_run("{0: ^{1}}".format(detailed_time,len(detailed_time)+6)).underline =True
paragraph_3.add_run(word_6)
paragraph_3.paragraph_format.line_spacing =1.5
word_7 ='申请⼈:'
paragraph_4 = doc.add_paragraph()
paragraph_4.add_run(word_7)
paragraph_4.add_run("{0: ^{1}}".format(name,len(name)+6)).underline =True
paragraph_4.alignment = WD_ALIGN_PARAGRAPH.RIGHT
word_8 ='⽇期:'
today_year = day().year
today_month = day().month
today_month = day().month
today_day = day().day
sign_date ="{}年{}⽉{}⽇".format(today_year,today_month,today_day)
paragraph_5 = doc.add_paragraph()
paragraph_5.add_run(word_8)
paragraph_5.add_run("{0: ^{1}}".format(sign_date,len(sign_date)+6)).underline =True
paragraph_5.alignment = WD_ALIGN_PARAGRAPH.RIGHT
for paragraph in doc.paragraphs:
for run in paragraph.runs:
b = RGBColor(0,0,0)
run.font.name ='微软雅⿊'
r = run._element.rPr.rFonts
r.set(qn('w:eastAsia'),'微软雅⿊')
doc.save("{}-请假条.docx".format(name))
print("-"*30)
print("\n{}的请假条已经⽣成\n\n⽂件位置在:{}\n\n⽂件名称为:{}-请假条.docx".format(wd(),name))
⾄此利⽤python⾃动⽣成请假条的代码就全部执⾏完毕,应⽤的难点在于输⼊⽂字下划线的显⽰问题,如果直接对输⼊的⽂字加下划线,会显得很挤,如果单纯使⽤format()⽅法,⽣成的只⽤两侧下划线看上去很别扭,因此最终采取的⽅式是将两者结合,解决了输⼊字符下划线显⽰的问题,当然最后还有中⽂字符显⽰的问题
执⾏效果:
第⼆部分:看过程,踩过的坑
遇到报错:
ImportError: No module named 'exceptions'
(遇到问题不要慌,先拿出⼿机,发个盆友圈=v=/)
遇到这个问题的原因是:缺少python-docx这个包需要安装
这个⽹站中下载的docx是红⾊字体这个,不是链接⾥⾯那个(反正我不到)
(ps:链接⾥⾯的那个是这个
python_docx-0.8.6-py2.py3-none-any.whl
不出意外的话应该是不到,你可以⽤这个好像是最新的作⽤是⼀样的python_docx‑0.8.10‑py2.py3‑none‑any.whl)
⽤pip安装下来如果你不清楚下载后来路径肿么办,或者不太熟悉pip m命令可以参考这⼏篇⽂章
注意:要先⽤pip uninstall python-docx把原来的包删掉如果原来有的话
pip install 包名-t 路径

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。