Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用python xlwt库更改excel单元格的背景色?_Python_Xlwt - Fatal编程技术网

如何使用python xlwt库更改excel单元格的背景色?

如何使用python xlwt库更改excel单元格的背景色?,python,xlwt,Python,Xlwt,我使用Python库在excel工作簿中写入数据。 现在我在向excel单元格添加背景色时遇到了一些问题 例如,我有RGB中的下一种颜色(10,20,30),最简单的方法是什么? 有没有办法将此颜色设置为单元格 我只找到了与我的问题类似的帖子。在本例中,我演示了如何设置单元格的背景色,您可以运行它以获得结果: from xlwt import Workbook import xlwt book = Workbook() sheet1 = book.add_sheet('Sheet 1') for

我使用Python库在excel工作簿中写入数据。
现在我在向excel单元格添加背景色时遇到了一些问题

例如,我有RGB中的下一种颜色(10,20,30),最简单的方法是什么? 有没有办法将此颜色设置为单元格


我只找到了与我的问题类似的帖子。

在本例中,我演示了如何设置单元格的背景色,您可以运行它以获得结果:

from xlwt import Workbook
import xlwt
book = Workbook()
sheet1 = book.add_sheet('Sheet 1')
for i in range(0, 100):
    st = xlwt.easyxf('pattern: pattern solid;')
    st.pattern.pattern_fore_colour = i
    sheet1.write(i % 24, i // 24, 'Test text', st)
book.save('simple.xls')

我有这个问题,我做了很多搜索

最后,我在以下方面找到了一个合适且良好的解决方案:

它工作得很好

只需将此类添加到项目中并设置excel颜色:

class ColorMatcher(object):
"""
the source is in : http://www.archivum.info/python-excel@googlegroups.com/2012-09/00014/Re-(pyxl)-Re-Background-with-any-rgb-value.html

Prior to Excel 2007, Excel only had color
indexes, and that's all that xlwt supports.  Maybe this will help,
though.  It use a ColorMatcher that takes an RGB input and tries to
return the closest matching Excel color index:
"""

def __init__(self):
    self.reset()

def reset(self):
    self.unused_colors = set(self.xlwt_colors)
    # Never use black.
    self.unused_colors.discard((0, 0, 0))

#Culled from a table at http://www.mvps.org/dmcritchie/excel/colors.htm
xlwt_colors=[
    (0,0,0), (255,255,255), (255,0,0), (0,255,0), (0,0,255), (255,255,0),
    (255,0,255), (0,255,255), (0,0,0), (255,255,255), (255,0,0), (0,255,0),
    (0,0,255), (255,255,0), (255,0,255), (0,255,255), (128,0,0), (0,128,0),
    (0,0,128), (128,128,0), (128,0,128), (0,128,128), (192,192,192),
    (128,128,128), (153,153,255), (153,51,102), (255,255,204),
    (204,255,255), (102,0,102), (255,128,128), (0,102,204), (204,204,255),
    (0,0,128), (255,0,255), (255,255,0), (0,255,255), (128,0,128),
    (128,0,0), (0,128,128), (0,0,255), (0,204,255), (204,255,255),
    (204,255,204), (255,255,153), (153,204,255), (255,153,204),
    (204,153,255), (255,204,153), (51,102,255), (51,204,204), (153,204,0),
    (255,204,0), (255,153,0), (255,102,0), (102,102,153), (150,150,150),
    (0,51,102), (51,153,102), (0,51,0), (51,51,0), (153,51,0), (153,51,102),
    (51,51,153), (51,51,51)
]

@staticmethod
def color_distance(rgb1, rgb2):
    # Adapted from Colour metric by Thiadmer Riemersma,
    # http://www.compuphase.com/cmetric.htm
    rmean = (rgb1[0] + rgb2[0]) / 2
    r = rgb1[0] - rgb2[0]
    g = rgb1[1] - rgb2[1]
    b = rgb1[2] - rgb2[2]
    return (((512 + rmean) * r * r) / 256) + 4 * g * g\
    + (((767 - rmean) * b * b) / 256)

def match_color_index(self, color):
    """Takes an "R,G,B" string or wx.Color and returns a matching xlwt
    color.
    """
    if isinstance(color, int):
        return color
    if color:
        if isinstance(color, basestring):
            rgb = map(int, color.split(','))
        else:
            rgb = color.Get()
        distances = [self.color_distance(rgb, x) for x in self.xlwt_colors]
        result = distances.index(min(distances))
        self.unused_colors.discard(self.xlwt_colors[result])
        return result

def get_unused_color(self):
    """Returns an xlwt color index that has not been previously returned by
    this instance.  Attempts to maximize the distance between the color and
    all previously used colors.
    """
    if not self.unused_colors:
        # If we somehow run out of colors, reset the color matcher.
        self.reset()
    used_colors = [c for c in self.xlwt_colors if c not in
                                                  self.unused_colors]
    result_color = max(self.unused_colors,
        key=lambda c: min(self.color_distance(c, c2)
        for c2 in used_colors))
    result_index = self.xlwt_colors.index(result_color)
    self.unused_colors.discard(result_color)
    return result_index
此代码的来源是:

我建议使用XlsxWriter模块,它也有很棒的功能

嗨,Pooria,thnx作为答案,我尝试了你的代码,效果很好,但问题是你只使用预设颜色,但我只需要使用自定义RGB,例如,我有一系列颜色以RGB(1255255)开始,以RGB(255255)结束我需要将这个范围内的每种颜色都添加到excel中,我试图找到类似于addRGBColor(a,b,c)的方法。当然,如果它存在于xlwt Aphi Ishikawa中,我认为不可能设置rgbcolor。因为当我想在电子表格中选择一种颜色作为单元格的背景时,它只显示预设的颜色。但我不确定这是不可能的。我还没有安装excel,但我认为这将与电子表格相同。一个问题是,这是否允许有条件地为某些单元格着色?不再有“解决方案来源”链接。
GREEN_TABLE_HEADER = easyxf(
                 'font: bold 1, name Tahoma, height 160;'
                 'align: vertical center, horizontal center, wrap on;'
                 'borders: left thin, right thin, top thin, bottom thin;'
                 'pattern: pattern solid, pattern_fore_colour green, pattern_back_colour green'
                 )
overviewSheet.row(rowCursor).write(col_0, 'Issue', GREEN_TABLE_HEADER)