import docx
from docx.oxml.ns import qn
from docx.shared import Pt
newfile = docx.Document()
p1 = newfile.add_paragraph()
text1 = p1.add_run("第一段文字是中文;The first paragraph is in English")
p2 = newfile.add_paragraph()
text2 = p2.add_run("第二段文字是中文;The second paragraph is in English")
# 分别控制每个段落的字体
text1.font.size = Pt(15) # 字体大小
text1.bold = True # 字体是否加粗
text1.font.name = 'Times New Roman' # 控制是西文时的字体
text1.element.rPr.rFonts.set(qn('w:eastAsia'), '宋体') # 控制是中文时的字体
text2.font.size = Pt(10)
text2.bold = False # 字体是否加粗
text2.font.name = 'Times New Roman'
text2.element.rPr.rFonts.set(qn('w:eastAsia'), '黑体')
newfile.save("newdocx.docx")
上面代码是向文档写入了两段文字,第一段中的中文是“宋体”的,而第二段中的中文是“黑体”的。
补充:python 使用 python-docx 调整 Word 文档样式
修改文字字体样式
from docx import Document
from docx.shared import Pt #设置像素、缩进等
from docx.shared import RGBColor #设置字体颜色
from docx.oxml.ns import qn
doc = Document(r"../wordDemo/表彰大会通知.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,0,255)
run.font.name = "黑体"
# 设置像黑体这样的中文字体,必须添加下面 2 行代码
r = run._element.rPr.rFonts
r.set(qn("w:eastAsia"),"黑体")
doc.save(r"../wordDemo/表彰大会通知.docx")
修改段落样式
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH #设置对象居中、对齐等。
doc = Document(r"../wordDemo/表彰大会通知.docx")
print(doc.paragraphs[1].text)
doc.paragraphs[1].alignment = WD_ALIGN_PARAGRAPH.CENTER
# 这里设置的是居中对齐
doc.save(r"../wordDemo/表彰大会通知.docx")
行间距调整
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
doc = Document(r"../wordDemo/表彰大会通知.docx")
for paragraph in doc.paragraphs:
paragraph.paragraph_format.line_spacing = 5.0
doc.save(r"../wordDemo/表彰大会通知.docx")
段前与段后间距
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Pt
doc = Document(r"../wordDemo/test.docx")
for paragraph in doc.paragraphs:
paragraph.paragraph_format.space_before = Pt(12)
paragraph.paragraph_format.space_after = Pt(10)
# Pt(12) 表示12磅
doc.save(r"../wordDemo/test.docx")