I want to generate an Excel file with several strings across the cells, and mark some parts of each string with a set of colors.
This is an example if I just wanted to mark a fixed part of a single text:
import xlsxwriter
outfile = xlsxwriter.Workbook('file.xlsx')
sheet = outfile.add_worksheet()
bold_red = outfile.add_format({'bold': True,'font_color':'red', 'underline': True})
sheet.write_rich_string(0,0,"This text in black, ",bold_red,"this one in red & bold, ","and this -probably- in other color")
outfile.close()
The result is an Excel file with a cell this text in "A1":
I tried passing a variable input to write_rich_string
, but the content of bold_red
is xlsxwriter.format.Format
and cannot concatenate with strings.
This is how it looks without the colors:
This is the expected output:
In this link by @jmcnamara I found the answer:
"If you have formats and segments in a list you can add them like this, using the standard Python list unpacking syntax:"
segments = ['This is ', bold, 'bold', ' and this is ', blue, 'blue']
worksheet.write_rich_string('A9', *segments)
So for each "Text" in my dataframe, will get its pattern for coloring from a external key.
Then form a list with pieces of text and formats embedded.
Finally pass this list as a parameter to write_rich_string
.