newfile = docx.Document()
newfile.styles['Normal'].font.name = 'Times New Roman'
newfile.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋體')
設定字型的兩句一定要一起用才能起作用,其中
newfile.styles['Normal'].font.name = 'Times New Roman' 是用來設定當文字是西文時的字型,
newfile.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋體') 是用來設定當文字是中文時的字型。
有點類似Word中的
當只要設定一部分文字的字型,即不要整個檔案的字型都一樣時,可以用以下方法:
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")
以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。如有錯誤或未考慮完全的地方,望不吝賜教。