python-docx之应用

这篇博客介绍了如何在Python环境下,利用python-docx库创建和修改Word文档的样式,包括设置字体、大小、颜色和对齐方式。内容涵盖了自定义段落、字符和表格样式,以及调整内置的正文和标题样式,确保中英文字体设置正确。
摘要由CSDN通过智能技术生成

一、软件版本

(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'宋体')。

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值