简体   繁体   中英

How to set color of text using xlwt

I haven't been able to find documentation on how to set the color of text. How would the following be done in xlwt?

style = xlwt.XFStyle()

# bold
font = xlwt.Font()
font.bold = True
style.font = font

# background color
pattern = xlwt.Pattern()
pattern.pattern = xlwt.Pattern.SOLID_PATTERN
pattern.pattern_fore_colour = xlwt.Style.colour_map['pale_blue']
style.pattern = pattern

# color of text
???

Another way I have tried, where I've been able to set the font color but not the background color is:

style = xlwt.easyxf('font: bold 1, color red;')

This is what worked:

style = xlwt.easyxf('pattern: pattern solid, fore_colour light_blue;'
                              'font: colour white, bold True;')

设置“colour_index”属性。

   style.font.colour_index = xlwt.Style.colour_map['white']

Alternative solution:

If you can get away with the colors defined in xlwt , go to a color information site like http://www.colorhexa.com/90ee90 and get the closest match.

For the font color font.color should do it where for the cell background color there is a similar question:

python xlwt set custom background colour of a cell

I would recommend using the following code:

from xlwt import Workbook,XFStyle,Borders, Pattern, Font, easyxf

styleOK = easyxf('pattern: fore_colour light_blue;'
                          'font: colour green, bold True;')
from xlwt import *
import xlwt

w = Workbook()
sheet1= w.add_sheet('Test')

st = xlwt.easyxf('pattern: pattern solid;')
st.pattern.pattern_fore_colour = 20 #random color number
sheet1.write(0, 0,'Random Text',st)

w.save('Random_xls.xls')

style = xlwt.easyxf('pattern: pattern solid, fore_colour light_blue;' 'font: colour white, bold True;')

    sheet.write(row, 0, "Code", style)
    sheet.write(row, 1, "Name", style)
    sheet.write(row, 2, "bottle",style)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM