、利用Python调整Word文档样式
1)修改文字字体样式
from docx import Document
from docx.shared import Pt,RGBColor
from docx.oxml.ns import qn
doc = Document(r"G:\6Tipdm\7python办公自动化\concat_word\test2.docx")
for paragraph in doc.paragraphs:
for run in paragraph.runs:
run.font.bold = True
run.font.italic = True
run.font.underline = True
run.font.strike = True
run.font.shadow = True
run.font.size = Pt(18)
run.font.color.rgb = RGBColor(255,255,0)
run.font.name = "宋体"
# 设置像宋体这样的中文字体,必须添加下面2行代码
r = run._element.rPr.rFonts
r.set(qn("w:eastAsia"),"宋体")
doc.save(r"G:\6Tipdm\7python办公自动化\concat_word\_test1.docx")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
结果如下:
2)修改段落样式
① 对齐样式
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
doc = Document(r"G:\6Tipdm\7python办公自动化\concat_word\test1.docx")
print(doc.paragraphs[0].text)
doc.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
# 这里设置的是居中对齐
doc.save(r"G:\6Tipdm\7python办公自动化\concat_word\对齐样式.docx")
"""
LEFT,CENTER,RIGHT,JUSTIFY,DISTRIBUTE,JUSTIFY_MED,JUSTIFY_HI,JUSTIFY_LOW,THAI_JUSTIFY
"""
1
2
3
4
5
6
7
8
9
10
11
结果如下:
② 行间距调整
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
doc = Document(r"G:\6Tipdm\7python办公自动化\concat_word\test1.docx")
for paragraph in doc.paragraphs:
paragraph.paragraph_format.line_spacing = 5.0
doc.save(r"G:\6Tipdm\7python办公自动化\concat_word\行间距.docx")
1
2
3
4
5
6
7
结果如下:
③ 段前与段后间距
网站声明:如果转载,请联系本站管理员。否则一切后果自行承担。
添加我为好友,拉您入交流群!
请使用微信扫一扫!