gpt4 book ai didi

python - 如何使用 python-docx 更改标题样式?

转载 作者:行者123 更新时间:2023-12-03 08:35:57 32 4
gpt4 key购买 nike

我正在使用 python-docx 但我不理解或检索任何更改标题样式(从粗体到正常)的方法。我的代码是:

import docx
from docx.shared import RGBColor
from docx.shared import Pt
from docx.dml.color import ColorFormat
from docx.enum.style import WD_STYLE_TYPE

#format only the filename as return text
def format_filename(fname):
index = fname.rfind('\\')
font.color.rgb = RGBColor(255,0,0)
#IF statement for structuring the fine name
if index>0:
filename = fname[index + 1, len(fname)]
else:
index = fname.rfind('/')
filename = fname[index + 1 : len(fname)]
return filename

#print all the file into docx
def print_file(file):
font.bold = False
font.color.rgb = RGBColor(0,0,0)
cnt = 0
fp = open(file, 'r')
#read all the file and use every single line
for line in fp.readlines():
cnt += 1
#if it's the first line add paragraph
if cnt == 1:
paragraph = document.add_paragraph(line)
#else continue the paragraph
else:
paragraph.add_run(line)

#open file
document = docx.Document()
filepath = '../cap1/prg1.txt'

# set the font in the paragraph
run = document.add_paragraph().add_run()
style = document.styles['Normal']
font = style.font
font.name = 'Courier New'
font.size = Pt(10.5)
font.bold = True
font.color.rgb = RGBColor(255,0,0)

#print as a heading the filename
filename = format_filename(filepath) #self procedure for format the filename
document.add_heading(filename , level=2)
#print all the file
print_file(filepath)

document.save('my_cake_file.docx')

这是标题着色后的样子:

title after coloring

最佳答案

您需要更新 Heading 2 样式的颜色。这是示例:

import docx

# Create doc
document = docx.Document()

# Add black title
styles = document.styles
styles['Heading 2'].font.color.rgb = docx.shared.RGBColor(0, 0, 0)
document.add_heading('Title', level=2)

# Add text
paragraph = document.add_paragraph()
paragraph.add_run('text')

# Save file
document.save('output.docx')

输出:

enter image description here

关于python - 如何使用 python-docx 更改标题样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63831761/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com