使用Python xlsxwriter将可变的write_rich_string格式属性添加到文本中

问题描述 投票:1回答:1

我想生成一个在单元格中具有多个字符串的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”中:

enter image description here

我尝试将变量输入传递给write_rich_string,但bold_red的内容为xlsxwriter.format.Format,并且无法与字符串连接。

这是没有颜色的外观:

This is how it looks without the colors

这是预期的输出:

Variable coloring, depending on outside variables

python xlsxwriter richtext
1个回答
1
投票

在@jmcnamara的link中,我找到了答案:

“如果列表中有格式和句段,则可以使用标准的Python列表解包语法将其添加为此类:”

segments = ['This is ', bold, 'bold', ' and this is ', blue, 'blue']
worksheet.write_rich_string('A9', *segments)

因此,对于数据框中的每个“文本”,将从外部键获取其着色模式。然后形成一个列表,其中嵌入了一些文本和格式。最后将此列表作为参数传递给write_rich_string

© www.soinside.com 2019 - 2024. All rights reserved.