What you are looking for is rich text. Unfortunately, openpyxl
does not, and apparently will not, support it. From this (closed) issue in the OpenPyXL repo: "This [rich text] cannot be done without adding a great deal of complexity to the library." Charlie Clark, one of the creators of OpenPyXL, says as much in this Stack Overflow answer. So, while you can format text in cells (bolding, choosing a font, coloring the text, etc.), you cannot mix formats such as what you're looking for. You can only apply one set of formatting rules to the entire string of text.
However, the xlsxwriter
library does this very task with ease. From this example, you can mix bold and italic in the same cell:
# Copyright 2013-2021, John McNamara, jmcnamara@cpan.org
#
import xlsxwriter
workbook = xlsxwriter.Workbook('rich_strings.xlsx')
worksheet = workbook.add_worksheet()
worksheet.set_column('A:A', 30)
# Set up some formats to use.
bold = workbook.add_format({'bold': True})
italic = workbook.add_format({'italic': True})
worksheet.write_rich_string('A1',
'This is ',
bold, 'bold',
' and this is ',
italic, 'italic')
workbook.close()
I don't know offhand if the OpenPyXL and xlsxwriter Workbook and Worksheet objects are compatible, so you'll need to do some testing. If they aren't, you may need to refactor your code some in order to use the rich text feature of xlsxwriter.
Finally, it's worth noting that there are other Excel-interfacing Python modules, such as PyXLL and XLWings that can handle pretty much any Excel operation or feature because the use COM to tie directly into the program. However, you need a copy of Excel on the computer you're running the script on, and you may need to install plugins into Excel as well.