python中docx库的使用一
创建word文档,并添其中插入文字及图片
docx库,可以用来创建docx文档,包含段落、分页符、表格、图片、标题、样式等几乎所有的word文档中能常用的功能都包含了,这个包的主要功能便是用来创建文档,相对来说用来修改功能不是很强大。
首先检查一下我们的的python中是否有docx这个库,如果没有我们就需要安装一下。
用代码创建一个简单的word文档,并在文档中写一首诗如下:
效果展示:
编写的代码如下:
import docx
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn
document = docx.Document() #创建一个Document对象(word文件)
print(document) #<docx.document.Document object at 0x0000021867D29DC8>
document1 = document.add_paragraph('静夜思') #在word文档中插入‘静夜思’
document1.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER #‘静夜思’居中
#插入古诗
lv_0 = document.add_paragraph(' --李白')
lv_0.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
lv_1 = document.add_paragraph('床前明月光,',style='List Bullet')
lv_1.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
lv_2 = document.add_paragraph('疑是地上霜。',style='List Bullet')
lv_2.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
lv_3 = document.add_paragraph('举头望明月,',style='List Bullet')
lv_3.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
lv_4 = document.add_paragraph('低头思故乡。',style='List Bullet')
lv_4.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
#设置word文档中的字体格式
document.styles['Normal'].font.name = u'华文行楷'
document.styles['Normal'].element.rPr.rFonts.set(qn('w:eastAsia'), u'华文行楷')
#插入照片
document.add_picture(r'C:\Users\Admin\Desktop\timg.jpg',width=docx.shared.Inches(6))
document.save('静夜思.docx')#保存word文档,并命名为‘静夜思’
``