Write pandas dataframe to Excel with xlsxwriter and include `write_rich_string` formatting
I'm not sure that my answer is much better than the way you do it, but I've cut it down to use only one for loop and make use of pandas.DataFrame.to_excel()
to initially put the dataframe in excel. Please note that I then overwrite the last column using worksheet.write_rich_string()
.
import pandas as pd
writer = pd.ExcelWriter('pandas_with_rich_strings.xlsx', engine='xlsxwriter')
workbook = writer.book
bold = workbook.add_format({'bold': True})
italic = workbook.add_format({'italic': True})
red = workbook.add_format({'color': 'red'})
df = pd.DataFrame({
'numCol': [1, 50, 327],
'plainText': ['plain', 'text', 'column'],
'richText': [
['This is ', bold, 'bold'],
['This is ', italic, 'italic'],
['This is ', red, 'red']
]
})
df.to_excel(writer, sheet_name='Sheet1', index=False)
worksheet = writer.sheets['Sheet1']
# you then need to overwite the richtext column with
for idx, x in df['richText'].iteritems():
worksheet.write_rich_string(idx + 1, 2, *x)
writer.save()
With Expected Outputted .xlsx: