Python xlsxwriter write_rich_string 并突出显示

Python xlsxwriter write_rich_string and highlight

我使用 xlsxwriter 生成 excel 报告。由于 write_rich_string 方法,我想在文本的一部分下划线。

format = {
    'text': self.formats.result,
    'difference': self.formats.difference_result
}
args = [self.current_line, _column]
for diff in _diff:
    args.append(format.get(diff.get('kind')))
    args.append(diff.get('text'))
args.append(self.formats.result)
self.worksheet.write_rich_string(*args)

其中这些格式:

self.difference_result = self.workbook.add_format()
self.difference_result.set_font_color('yellow')
self.difference_result.set_fg_color('red')

self.result = self.workbook.add_format()
self.result.set_align('top')
self.result.set_text_wrap()
self.result.set_border(1)
self.result.set_border_color('gray')

我的问题是文本是黄色的,但没有用红色突出显示。 xlsxwriter 可以吗?

Is this possible with xlsxwriter?

一般来说,如果格式可以在 Excel 中实现,那么在 XlsxWriter 中也是可以的,因为它支持 Excel 的所有单元格格式。

很遗憾,Excel 中无法执行您尝试执行的操作。来自 write_rich_string() docs:

In Excel only the font properties of the format such as font name, style, size, underline, color and effects are applied to the string fragments in a rich string. Other features such as border, background, text wrap and alignment must be applied to the cell.

这个有效:

import xlsxwriter
outfile  = xlsxwriter.Workbook('file.xlsx')
sheet    = outfile.add_worksheet()
underlin = outfile.add_format({'underline': True})
sheet.write_rich_string(0,0,"This text as usual, ",underlin,"this underlined, ","and this as usual")
outfile.close()