如何在 python docx 中加粗行单元格的文本?

How to bold the text of a row cells in python docx?

我正在使用 python docx 模块生成文档。 我想在 python docx

中加粗一行的特定单元格

这是代码

book_title = '\n-:\n {}\n\n'.format(book_title)
book_desc = '-: {}\n\n:\n{}\n\n :\n{}'.format(book.author,book_description,sales_point)


row1.cells[1].text = (book_title + book_desc)

我只想加粗 book_title。 如果我应用一种样式,它会自动应用于整个文档。

由于您使用的是 docx 模块,因此您可以通过显式定义样式来设置 text/paragraph 样式。

要应用样式,请使用从 docx 文档中引用的以下代码片段 here

>>> from docx import Document
>>> document = Document()
>>> style = document.styles['Normal']
>>> font = style.font
>>> font.bold= True

这会将应用段落的字体样式更改为粗体。

以下是我的理解: 段落包含 运行 个对象,样式(粗体、斜体)是 运行 的方法。 所以按照这里的逻辑可能会解决你的问题:

row1_cells[0].paragraphs[0].add_run(book_title + book_desc).bold=True

这只是 table 第一个单元格的示例。请在您的代码中修改。

在 python-docx 中,可以使用 Rich Text 样式覆盖 docx 模板文档中任何字符的样式。您应该为需要在模板中设置样式的特定 character/string 在 character/string 的位置提供上下文变量。此变量映射到具有样式定义(您在代码中定义)的 RichText 对象,以设置 character/string 的样式。为了使事情更清楚,请考虑包含以下文本的示例模板文档“test.docx”:

Hello {{r context_var}}!

{{..}} 是 jinja2 标签语法,{{r 是覆盖字符样式的 RichText 标签。 context_var 是一个将样式映射到字符串的变量。 我们像这样完成富文本样式:

from docxtpl import DocxTemplate, RichText
doc = DocxTemplate("test.docx")
rt = RichText() #create a RichText object
rt.add('World', bold=True) #pass the text as an argument and the style, bold=True
context = { 'context_var': rt } #add context variable to the context and map it to rt
doc.render(context) #render the context
doc.save("generated_doc.docx") #save as a new document

我们来看看“generated_doc.docx”的内容:

Hello World!

我不确定你的模板是如何设计的,但如果你只想将 book_title 设为粗体,你的模板“test.docx”应该包含如下文本:

Title:-

{{r book_title_var}}

代码应修改为:

book_title = "Lord of the Rings" #or wherever you get the book title from
rt.add(book_title, bold=True)
context = { 'book_title_var': rt }

generated_doc.docx:

Title:-

Lord of the Rings

一个单元格没有字符样式;字符样式只能应用于文本,尤其是 运行 文本。这实际上是 运行 的定义特征,是共享相同字符格式的字符序列,在 python-docx 中也称为 font

要获得与描述不同字体的书名,它们需要出现在单独的 运行 中。分配给 Cell.text(如您所愿)会导致所有文本都在一个 运行.

这可能对您有用,但假设您开始时单元格为空:

paragraph = row1.cells[1].paragraphs[0]
title_run = paragraph.add_run(book_title)
description_run = paragraph.add_run(book_desc)
title_run.bold = True

这段代码可以做得更紧凑:

paragraph = row1.cells[1].paragraphs[0]
paragraph.add_run(book_title).bold = True
paragraph.add_run(book_desc)

但也许以前的版本更清楚地说明了您在每个步骤中所做的事情。