Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am generating a doc using python docx module. I want to bold the specific cell of a row in python docx

here is the code

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)

I just want to bold the book_title. If I apply a style it automatically applies to whole document.

like image 796
Mandeep Thakur Avatar asked Aug 31 '25 00:08

Mandeep Thakur


2 Answers

A cell does not have a character style; character style can only be applied to text, and in particular to a run of text. This is in fact the defining characteristic of a run, being a sequence of characters that share the same character formatting, also known as font in python-docx.

To get the book title with a different font than the description, they need to appear in separate runs. Assigning to Cell.text (as you have) results in all the text being in a single run.

This might work for you, but assumes the cell is empty as you start:

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

This code can be made more compact:

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

but perhaps the former version makes it more clear just what you're doing in each step.

like image 138
scanny Avatar answered Sep 06 '25 19:09

scanny


Here is how I understand it: Paragraph is holding the run objects and styles (bold, italic) are methods of run. So following this logic here is what might solve your question:

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

This is just an example for the first cell of the table. Please amend it in your code.

like image 24
NAS Avatar answered Sep 06 '25 17:09

NAS