python - 如何使用 python-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')
这是标题在着色后的样子:
解决方案
您需要更新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')
输出:
推荐阅读
- multithreading - 如何为 Rust 中的不同线程克隆随机数生成器?
- wordpress - 如何在 WooCommerce 中的变体标题旁边添加工具提示?
- faunadb - 索引完全在动物区数据库中返回“数据”字段
- android - Android:注入了 hilt throws 的 ViewModel 没有零参数构造函数”
- node.js - “无法读取未定义的属性‘url’”,即使它已经定义
- python - InvalidArgumentError:logits 和标签必须是可广播的:logits_size=[10,10] labels_size=[100,10]
- python - python将字符序列拆分为单独的列表
- sql - Sql根据多列的固定值将行拆分为多行
- python - 读取文件中的行,然后添加直到有一定数量的行
- java - Apache Camel 使用 JSON 路径表达式测试并断言 JSON 正文字段值