Excel 列比较使用 python 和格式化颜色

Excel column comparison using python and format the color

我有两列包含 2017 年值和 2018 年值。 我想根据与 2017 年值的比较为具有 2018 年值的列着色

  1. 如果 2018 单元格值 <2017 单元格值,则 2018 单元格为红色
  2. 如果 2018 单元格值 > 2017 单元格值,则 2018 单元格为绿色
  3. 如果 2018 单元格值 = 2017 单元格值,则 2018 单元格为橙色

我能够使用条件格式,但为此我必须创建一个新列来比较 A 列和 B 列

worksheet.write('C' + str(rownum + 1), np.where((float(data['2018 YTD'].values[0])>float(data['2017 YTD'].values[0])),2,np.where((float(data['2018 YTD'].values[0])>float(data['2017 YTD'].values[0])),0,1)), style)


worksheet.conditional_format('C2:C5',{'type': 'icon_set','icon_style': '3_arrows' })

但是使用此代码我不得不在此处再创建一列(C 列),相反,我希望直接使用颜色代码突出显示 B 列。

按照 Wald 的建议编辑 1##:

ws = wb.active 

redFill = PatternFill(start_color='FFFF0000', end_color='FFFF0000', fill_type='solid') 
GreenFill = PatternFill(start_color='EE1111', end_color='EE1111', fill_type='solid') 

if(ws['B2']>ws['A2']):
  ws['B2'].fill=redFill 
else(ws['B2']<ws['A2']):
  ws['B2'].fill=GreenFill

wb.save("sample.xlsx") 

但它给出了以下错误:

TypeError: '>' not supported between instances of 'Cell' and 'Cell'

似乎在这个包>或<不支持比较

在互联网上找到 this 库并测试了这个位,它按预期工作,没有任何不同颜色的逻辑。

from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.styles import PatternFill

wb = load_workbook("sample.xlsx")

ws = wb.active

redFill = PatternFill(start_color='FFFF0000',
               end_color='FFFF0000',
               fill_type='solid')

ws['A2'].fill = redFill

wb.save("sample.xlsx")

希望这对您有所帮助。

编辑

为了比较您需要使用单元格内的值而不是实际单元格中的值。

尝试if ws['B2'].value > ws['A2'].value:

您不能只使用自定义公式来设置条件格式而不是创建一个全新的行吗:

# First define some formats (taken directly from the docs: http://xlsxwriter.readthedocs.io/working_with_conditional_formats.html)
# Light red fill with dark red text.
red_format = workbook.add_format({'bg_color':   '#FFC7CE',
                                  'font_color': '#9C0006'})

# Light yellow fill with dark yellow text.
orange_format = workbook.add_format({'bg_color':   '#FFEB9C',
                                     'font_color': '#9C6500'})

# Green fill with dark green text.
green_format = workbook.add_format({'bg_color':   '#C6EFCE',
                                    'font_color': '#006100'})


# Red
worksheet.conditional_format('C2:C5', {'type':'formula',
                                       'criteria':'=C2<B2',
                                       'format':red_format})

# Orange
worksheet.conditional_format('C2:C5', {'type':'formula',
                                       'criteria':'=C2=B2',
                                       'format':orange_format})

# Green
worksheet.conditional_format('C2:C5', {'type':'formula',
                                       'criteria':'=C2>B2',
                                       'format':green_format})

您创建其中三个,一个用于绿色,一个用于橙色,一个用于红色,即您在 Excel.

中的做法