Home » excel » python – Write a part of a cell with different color in a XLS or CSV file

python – Write a part of a cell with different color in a XLS or CSV file

Posted by: admin May 14, 2020 Leave a comment

Questions:

Is there a way to write a part of a cell in colors in a CSV or XLS file? I am using Python and for presenting my results I want to use colors to highlight a part of a cell. The cell contains texts. If there is no any way to do that with XLS, what is the best alternative?

How to&Answers:

If you can use xlsx instead of xls/csv then you can use XlsxWriter’s write_rich_string() method:

import xlsxwriter

workbook = xlsxwriter.Workbook('rich_strings.xlsx')
worksheet = workbook.add_worksheet()

worksheet.set_column('A:A', 30)

# Set up some formats to use.
red = workbook.add_format({'color': 'red'})
blue = workbook.add_format({'color': 'blue'})

worksheet.write_rich_string('A1',
                            'This is ',
                            red, 'red',
                            ' and this is ',
                            blue, 'blue')

workbook.close()

Output:

enter image description here

See the XlsxWriter docs on write_rich_string()