24

我正在使用 python 2.7 和 xlwt 模块进行 excel 导出

我想设置我知道我可以使用的单元格的背景颜色

style1 = xlwt.easyxf('pattern: pattern solid, fore_colour red;')

但我想设置自定义颜色。像#8a8eef 或者是否有可能的颜色调色板,因为浅蓝色不起作用:)

谢谢你

4

5 回答 5

35

如今,有一种方法(最初在这里add_palette_colour()提出)使用and来定义和使用自定义颜色set_colour_RGB()

这是一个例子:

import xlwt


book = xlwt.Workbook()

# add new colour to palette and set RGB colour value
xlwt.add_palette_colour("custom_colour", 0x21)
book.set_colour_RGB(0x21, 251, 228, 228)

# now you can use the colour in styles
sheet1 = book.add_sheet('Sheet 1')
style = xlwt.easyxf('pattern: pattern solid, fore_colour custom_colour')
sheet1.write(0, 0, 'Some text', style)

book.save('test.xls')

另请参阅导致这种情况发生的实际拉取请求。

于 2014-01-09T05:29:52.293 回答
13

If you are not using easyxf() and instead are building XFStyle object step by step, here is another way of using user friendly color names:

import xlwt

style = xlwt.XFStyle()
pattern = xlwt.Pattern()
pattern.pattern = xlwt.Pattern.SOLID_PATTERN
pattern.pattern_fore_colour = xlwt.Style.colour_map['dark_purple']
style.pattern = pattern
于 2013-03-05T17:59:11.333 回答
6

对于预定义的颜色,请xlwt.Style._colour_map_text参见Style.py

要使用自定义颜色,您可能必须重新定义调色板,因为颜色不是直接在单元格中使用,而是作为调色板中颜色的索引。我不知道如何扩展调色板。对不起。

于 2011-10-12T21:44:05.213 回答
2

替代解决方案:

如果您可以摆脱 xlwt 中定义的颜色,请访问颜色信息网站,如http://www.colorhexa.com/90ee90,并从以下 Python Excel 颜色之一进行匹配:http: //bit.ly/1NMH67F

于 2015-04-03T11:34:35.100 回答
2

我推荐使用 XlsxWriter,它也有很棒的功能。 http://xlsxwriter.readthedocs.io/

于 2017-07-06T21:38:50.280 回答