python-docx生成word文档

python-docx

安装依赖包
pip install python-docx
官方文档:
https://python-docx.readthedocs.io/en/latest/index.html
官方实例非常简洁清晰的展示了python-docx生成的文档所包含的大部分功能:各级标题、增加图片、添加表格
官方实例.png

如下介绍三种其他常用配置

from docx.shared import Inches,RGBColor,Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn

doc = Document()
#1设置字体为微软雅黑 ,其他字体配置可在文档中找
doc.styles['Normal'].font.name = '微软雅黑'
doc.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'),'微软雅黑')
# 标题
p = doc.add_heading('标题',1)
#2设置文本居中
p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
#3设置字体颜色
color_red = RGBColor(*(255,0,0))
p.add_run('我是红色').font.color.rgb = color_red
posted @ 2019-08-31 13:24  古月月月胡  阅读(1750)  评论(0编辑  收藏  举报