openpyxl条件格式设置数字格式

时间:2015-11-12 21:00:22

标签: python-3.x conditional-formatting openpyxl

我正在尝试以条件格式设置数字格式。我已经找到了如何设置字体,边框和填充颜色,但我无法设置数字格式。我目前的代码是:

from openpyxl import load_workbook
from openpyxl.styles import PatternFill, Font, Border, Side
from openpyxl.formatting.rule import FormulaRule, DifferentialStyle, Rule

wb = load_workbook(filename='Excel_Templates\MyTemplate.xlsx')
ws = wb.get_sheet_by_name('Sheet1')
red_fill = PatternFill(start_color='FFFF0000', end_color='FFFF0000', fill_type='solid')
pink_fill = PatternFill(start_color='FFFF5050', end_color='FFFF5050', fill_type='solid')
light_pink_fill = PatternFill(start_color='FFFF9B99', end_color='FFFF9B99', fill_type='solid')
blue_fill = PatternFill(start_color='FF0000FF', end_color='FF0000FF', fill_type='solid')
light_blue_fill = PatternFill(start_color='FF0066FF', end_color='FF0066FF', fill_type='solid')
v_light_blue_fill = PatternFill(start_color='FF9BC2E6', end_color='FF9BC2E6', fill_type='solid')

side = Side(style='thin', color='FF000000')
myBorder = Border(left=side, right=side, bottom=side, top=side)
my_white_font = Font(color='FFFFFFFF', size=12)
my_black_font = Font(size=12)
p='E3'
num = 'E8'
denom = 'E9'
ws['{0}'.format(p)] = '=IF({0}/{1} >= 2, {0}/{1}, IF(AND({0}/{1}>=0, {0}/{1} <2),{0}/{1}-1, 1-{0}/{1}))'.format(
    num, denom)

    ws.conditional_formatting.add('{0}'.format(p),
                              FormulaRule(formula=['{0} < -0.5'.format(p)], fill=red_fill, font=my_black_font))

ws.conditional_formatting.add('{0}'.format(p),
                              FormulaRule(formula=['AND({0} < -0.25, {0} >=-0.5)'.format(p)], fill=pink_fill,
                                          font=my_black_font))

ws.conditional_formatting.add('{0}'.format(p),
                              FormulaRule(formula=['AND({0} < 0, {0} >=-0.25)'.format(p)], fill=light_pink_fill,
                                          font=my_black_font))

ws.conditional_formatting.add('{0}'.format(p),
                              FormulaRule(formula=['AND({0} >=0, {0} < 1)'.format(p)], fill=v_light_blue_fill,
                                          font=my_black_font))

ws.conditional_formatting.add('{0}'.format(p),
                              FormulaRule(formula=['AND({0} >=1, {0} <= 3)'.format(p)], fill=light_blue_fill,
                                          font=my_white_font))

ws.conditional_formatting.add('{0}'.format(p),
                              FormulaRule(formula=['{0} > 3'.format(p)], fill=blue_fill,
                                          font=my_white_font))

我想将格式设置为百分比,前4种格式没有小数点,我想将其设置为“+”0.0“X”表示最后两种格式。我查看了源代码,找不到这样做的方法。任何帮助,将不胜感激。我正在使用Python 3和Openpyxl 2.3.0与Excel 2010.

更新1:

我使用查理的建议更新了我的代码。我补充说:

dxf = DifferentialStyle(fill=blue_fill, font=my_white_font, numFmt='0.00%')
ws.conditional_formatting.add('{0}'.format(p), Rule(formula=['{0} > 3'.format(p)], dxf=dxf))

给出了以下错误消息。

File "C:\WinPython-32bit-3.4.3.3\python-3.4.3\lib\site-packages\openpyxl\styles\differential.py", line 57, in __init__
self.numFmt = numFmt
File "C:\WinPython-32bit-3.4.3.3\python-3.4.3\lib\site-packages\openpyxl\descriptors\base.py", line 42, in __set__
raise TypeError('expected ' + str(self.expected_type))
TypeError: expected <class 'openpyxl.styles.differential.NumFmt'>

更新2:

事实证明,Differential Style中的numFmt选项需要NumFmt的类实例,该实例在openpyxl.style.differential中定义。我将Update 1代码更改为以下内容:

from openpyxl.styles.differential import NumFmt
dxf = DifferentialStyle(fill=blue_fill, font=my_white_font, numFmt=NumFmt(10, '0.00%'))
r = Rule('expression', formula=['{0} > 3'.format(p)], dxf=dxf)
ws.conditional_formatting.add('{0}'.format(p), r)

然而,当我打电话

时,这些工作还不错
wb.save("test.xlsx")

我收到以下错误消息

    File "C:/TestProj/openpyxl_test.py", line 90, in <module>
    wb.save("test.xlsx")
  File "C:\WinPython-32bit-3.4.3.3\python-3.4.3\lib\site-packages\openpyxl\workbook\workbook.py", line 263, in save
    save_workbook(self, filename)
  File "C:\WinPython-32bit-3.4.3.3\python-3.4.3\lib\site-packages\openpyxl\writer\excel.py", line 230, in save_workbook
    writer.save(filename, as_template=as_template)
  File "C:\WinPython-32bit-3.4.3.3\python-3.4.3\lib\site-packages\openpyxl\writer\excel.py", line 213, in save
    self.write_data(archive, as_template=as_template)
  File "C:\WinPython-32bit-3.4.3.3\python-3.4.3\lib\site-packages\openpyxl\writer\excel.py", line 87, in write_data
    self._write_worksheets(archive)
  File "C:\WinPython-32bit-3.4.3.3\python-3.4.3\lib\site-packages\openpyxl\writer\excel.py", line 158, in _write_worksheets
    xml = sheet._write(self.workbook.shared_strings)
  File "C:\WinPython-32bit-3.4.3.3\python-3.4.3\lib\site-packages\openpyxl\worksheet\worksheet.py", line 772, in _write
    return write_worksheet(self, shared_strings)
  File "C:\WinPython-32bit-3.4.3.3\python-3.4.3\lib\site-packages\openpyxl\writer\worksheet.py", line 223, in write_worksheet
    for cf in cfs:
  File "C:\WinPython-32bit-3.4.3.3\python-3.4.3\lib\site-packages\openpyxl\writer\worksheet.py", line 119, in write_conditional_formatting
    if rule.dxf != DifferentialStyle():
  File "C:\WinPython-32bit-3.4.3.3\python-3.4.3\lib\site-packages\openpyxl\styles\hashable.py", line 77, in __ne__
    return not self == other
  File "C:\WinPython-32bit-3.4.3.3\python-3.4.3\lib\site-packages\openpyxl\styles\hashable.py", line 73, in __eq__
    return self.key == other.key
  File "C:\WinPython-32bit-3.4.3.3\python-3.4.3\lib\site-packages\openpyxl\styles\hashable.py", line 65, in key
    self._key = hash(tuple(fields))
TypeError: unhashable type: 'NumFmt'

2 个答案:

答案 0 :(得分:2)

我强烈怀疑您的问题来源是openpyxl中的错误。问题似乎是NumFmt类不可清除。我认为这可能源于它来自Serialisable,而不是HashableObject。因此,它基本上缺少__hash__函数。我认为您可以通过向NumFmt类添加__hash__函数来解决此问题,如下所示:

class NumFmt(Serialisable):

    numFmtId = Integer()
    formatCode = String()

    def __init__(self,
                 numFmtId=None,
                 formatCode=None,
                ):
        self.numFmtId = numFmtId
        self.formatCode = formatCode

    def __hash__(self):
        return hash((self.numFmtId, self.formatCode))

有了这个,我能够得到以下示例:     来自openpyxl import load_workbook     来自openpyxl.styles导入PatternFill     来自openpyxl.formatting.rule导入DifferentialStyle,Rule     来自openpyxl.styles.differential import NumFmt

wb = load_workbook(filename=r'C:\users\vanhamme\Desktop\foobar.xlsx')
ws = wb['Sheet1']

blue_fill = PatternFill(start_color='FF0000FF', end_color='FF0000FF', fill_type='solid')

dxf = DifferentialStyle(fill=blue_fill, numFmt=NumFmt(10, '0.00%'))
rule = Rule('expression', formula=['E3 > 3'], dxf=dxf)
ws.conditional_formatting.add('E3', rule)

wb.save(r'C:\users\vanhamme\Desktop\foobar2.xlsx')

这可能不是最优雅的解决方案。不幸的是,我不太了解openpyxl类层次结构,知道是否有更短,更清晰的路径。

答案 1 :(得分:0)

直接使用openpyxl.formatting.rule.Rule进行完全控制。 FormulaRule仅用于向后兼容,并未公开所有可能性,但如果查看其来源,您会看到可以传入DifferentialStyle的任何实例