我想生成一个在单元格中具有多个字符串的Excel文件,并用一组颜色标记每个字符串的某些部分。
这是一个示例,如果我只想标记单个文本的固定部分:
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()
结果是一个带有单元格的Excel文件,此文本在“ A1”中:
我尝试将变量输入传递给write_rich_string
,但bold_red
的内容为xlsxwriter.format.Format
,并且无法与字符串连接。
这是没有颜色的外观:
这是预期的输出:
在@jmcnamara的link中,我找到了答案:
“如果列表中有格式和句段,则可以使用标准的Python列表解包语法将其添加为此类:”
segments = ['This is ', bold, 'bold', ' and this is ', blue, 'blue']
worksheet.write_rich_string('A9', *segments)
因此,对于数据框中的每个“文本”,将从外部键获取其着色模式。然后形成一个列表,其中嵌入了一些文本和格式。最后将此列表作为参数传递给write_rich_string
。