导入需要的模块
from docx import Document
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.oxml.ns import qn
from docx.shared import Pt, RGBColor
1.打开word文档
"""变量名可以自定义"""
document = Document()
2.在正文应用字符样式(字体,大小,颜色)
# 设置正文字型 英文字型:Times New Roman; 中文字型:宋体
document.styles['Normal'].font.name = 'Times New Roman'
document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
# 设置正文字体大小
document.styles['Normal'].font.size = Pt(12)
# 设置正文字体颜色
document.styles['Normal'].font.color.rgb = RGBColor(0, 0, 0)
3.添加标题和段落
使用add_heading()方法添加标题
不推荐使用,标题格式比较特殊还需要后续处理。
content是要添加的内容。
level代表word文档内的标题等级,从0开始。
document.add_heading('content', level=1)
使用add_paragraph()方法添加段落
p_1 = document.add_paragraph('床前明月光\n疑是地上霜\n举头望明月\n低头思故乡', style='')
style设置段落样式,有两种类型:
①List Bullet:项目符号
②List Number:列表编号
4.设置段落对齐方式
paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
这里使用了CENTER这个枚举值。
对齐方式使用的枚举值 | |
LEFT |
左对齐 |
CENTER |
居中对齐 |
RIGHT |
右对齐 |
JUSTIFY |
两端对齐 |
DISTRIBUTE |
段落字符分布以填充段落的整个宽度 |
JUSTIFY_MED |
使用中等字符压缩率对齐 |
JUSTIFY_HI |
使用高字符压缩率进行对齐 |
JUSTIFY_LOW |
使用低字符压缩率进行对齐 |
THAI_JUSTIFY |
根据泰语格式布局对齐 |
5.设置粗体和斜体
这里引用一下官方文档的说明:
In order to understand how bold(粗体) and italic(斜体) work, you need to understand a little about what goes on inside a paragraph. The short version is this:
- A paragraph holds all the block-level(块级元素) formatting, like indentation(缩进), line height, tabs, and so forth.
- Character-level formatting, such as bold and italic, are applied at the run level(运行级别). All content within a paragraph must be within a run, but there can be more than one. So a paragraph with a bold word in the middle would need three runs, a normal one, a bold one containing the word, and another normal one for the text after.
When you add a paragraph by providing text to the method, it gets put into a single run. You can add more using the method on the paragraph:.
add_paragraph()
.add_run()
为此需要设置第一次运行的正常文本,这个文本可以为空。
P = document.add_paragraph('')
run = P.add_run("静夜思")
run.font.color.rgb = RGBColor(255, 0, 0)
run.font.size = Pt(14)
run.bold = True
P.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
6.指定路径并保存文件
filename = '静夜思'
document.save('D:\桌面\{}.docx'.format(filename))
7.最终效果
附图1——字号磅值对应表
字号 | 磅值 |
初号 | 42 |
小初 | 36 |
一号 | 26 |
小一 | 24 |
二号 | 22 |
小二 | 18 |
三号 | 16 |
小三 | 15 |
四号 | 14 |
小四 | 12 |
五号 | 10.5 |
小五 | 9 |
六号 | 7.5 |
小六 | 6.5 |
七号 | 5.5 |
八号 | 5 |
附图2——常用颜色RGB值对照表
常用颜色RGB值 | |||
颜色 | R | G | B |
黑色 | 0 | 0 | 0 |
白色 | 225 | 225 | 225 |
黄色 | 255 | 255 | 0 |
蓝色 | 0 | 0 | 255 |
红色 | 255 | 0 | 0 |
绿色 | 0 | 255 | 0 |
紫色 | 160 | 32 | 240 |
橙色 | 255 | 97 | 0 |