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

标签 python ms-word styles docx

我正在使用 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/

相关文章:

python - 如何让不和谐机器人说出接下来要播放的歌曲

php - LibreOffice 将 PDF 转换为 Word 作为文本框而不是普通文档

python - 使用正则表达式在文本文件中间隔单词

python - django - "manage.py test"失败 "table already exists"

c# - 图像(noninlineshape)从 Word 到剪贴板到文件

jquery - 使用 jQuery 切换样式,但不要全部更改

CSS:与另一个切换位置

标题中带有文本和图像的 Android ActionBar

python - 合并这些数据框时的 Nan 值

vba - 检测Word文档的语言