使用 Python xlsxwriter 将变量 write_rich_string 格式属性添加到文本
Adding variable write_rich_string format properties to a text with Python xlsxwriter
我想生成一个 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 中,我找到了答案:
"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)
因此,对于我的数据框中的每个 "Text",将从外部键获取其着色模式。
然后形成一个列表,其中嵌入了文本和格式。
最后将这个列表作为参数传递给 write_rich_string
.
我想生成一个 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 中,我找到了答案:
"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)
因此,对于我的数据框中的每个 "Text",将从外部键获取其着色模式。
然后形成一个列表,其中嵌入了文本和格式。
最后将这个列表作为参数传递给 write_rich_string
.