一、软件版本
(1)系统平台:window10
(2)python版本:3.9
(3)python-docx版本:0.8.11
二、内容
2.1 导入库
import docx
from docx import Document # 用来建立一个word对象
from docx.shared import Pt # 用来设置字体的大小
from docx.shared import Inches # 设置单位(英寸)
from docx.oxml.ns import qn # 设置字体
from docx.shared import RGBColor # 设置字体的颜色
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT # WD_PARAGRAPH_ALIGNMENT枚举变量
其中 WD_PARAGRAPH_ALIGNMENT.LEFT :左对齐
WD_PARAGRAPH_ALIGNMENT.CENTER :居中
WD_PARAGRAPH_ALIGNMENT.LEFT :右对齐
2.2 样式
(1)添加自定义样式:
style_zhengwen = document.styles.add_style('style_zhengwen',1) # 设置段落样式
style_zhengwen = document.styles.add_style('style_zhengwen',2) # 设置字符样式
style_zhengwen = document.styles.add_style('style_zhengwen',3) # 设置表格样式
其中:1代表段落样式:应用于paragraph对象;
2代表字符样式:应用于run对象;
3代表表格样式:应用于table对象。
(2)修改自带样式
修改正文样式:
# 样式设置,正文1 = Normal1
Normal1 = document.styles['Normal'] # 设置段落样式
Normal1.font.name = 'Times New Roman' # 西文字体设置为Times New Roman
Normal1._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体') # 中文字体设置为宋体
Normal1.font.size = Pt(16) # 字体为四号
Normal1.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT # 左对齐
修改标题样式:
# 样式设置,标题2 = style_biaoti2
style_biaoti2 = document.styles['Heading 2'] # 设置段落样式
style_biaoti2.font.name = 'Times New Roman' # 西文字体设置为Times New Roman
style_biaoti2._element.rPr.rFonts.set(qn('w:eastAsia'), u"宋体") # 中文字体设置为宋体
style_biaoti2._element.rPr.rFonts.set(qn('w:eastAsiaTheme'), u"宋体") # 中文字体设置为宋体
style_biaoti2.font.size = Pt(14) # 字体为小四
style_biaoti2.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT # 左对齐
注意中文字体设置需要同时将 style_biaoti2 样式字体属性中的 w:eastAsia 、w:eastAsiaTheme 的属性同时修改为中文的格式(u'宋体')。