如何更改 docx 文件中的字体大小 python

How do I change font size in a docx file python

我正在尝试创建财务日志,但是我无法在不更改所有文本的整个字体大小的情况下将字体大小从一种大小更改为另一种大小。

我希望 "Finance Log" 和 "Created On..." 是 48 岁,"Log Begins:" 是 24 岁。

Tstyle = doc.styles['Normal']
font = Tstyle.font
font.name = "Nunito Sans"
font.size = Pt(48)
Title = doc.add_paragraph()
TRun = Title.add_run("Finance Log")
TRun.bold = True
CurrentDate= datetime.datetime.now()
FormattedDate= CurrentDate.strftime('%d-%m-%Y')
FCreated = Title.add_run("\nFile Created On "+FormattedDate)
Fstyle = doc.styles['Heading 1']
font = Fstyle.font
font.name = "Nunito Sans"
font.size = Pt(24)
FLog = doc.add_paragraph()
FinanceTitle = FLog.add_run("Log Begins:")
doc.save(path_to_docx)

我尝试了多种方法,例如创建新样式、将新样式设置为标题等...

我知道 但是我无法解决这个问题

I canot change the font size from one size to another without the entire font size of all the text changing.

那是因为您要更改 style 对象的基本字体大小:

Tstyle = doc.styles['Normal']
font = Tstyle.font  # << this line assigns font = doc.styles['Normal'].font

因此,您使用的不是通用 "font" 属性,而是属于命名样式 "Normal" 的字体。所以:

font.name = "Nunito Sans"
font.size = Pt(48)  # << this line changes the font size of doc.styles['Normal']

未经测试,但请尝试:

TStyle, FStyle = doc.styles['Normal'], doc.styles['Heading 1']
for style in (TStyle, FStyle):
    style.font.name = "Nunito Sans"
TStyle.font.size = Pt(48)
FStyle.font.size = Pt(24)


Title = doc.add_paragraph()
Title.style = TStyle
TRun = Title.add_run("Finance Log")
TRun.bold = True

FCreated = Title.add_run("\nFile Created On {0}".format(datetime.datetime.now().strftime('%d-%m-%y')))

FLog = doc.add_paragraph()
FLog.style = FStyle
FinanceTitle = FLog.add_run("Log Begins:")
doc.save(path_to_docx)