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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With