使用python在excel中进行背景单元格颜色控制

时间:2019-04-11 15:46:54

标签: python excel

我希望能够在excel中控制背景单元格的颜色。我的数据量很大,因此需要确定数据是否符合预期。我已经可以使用Python做到这一点。但是,我想在excel中显示此数据,并使其更易于阅读,我想根据数据的好坏为单元格上色。

我已经使用style.applymap根据特定的单元格值为单元格分配颜色。例如,如果单元格显示“失败”,那么我可以将其涂成红色。

因此,如果我遍历数据并创建一个新的“通过” /“失败”列表,并将这些值输入到excel文档中,则可以得到我想要的颜色。此代码如下所示,我可以获得类似The Pass/Fail column has 'pass' or 'fail' as text, and this is used to define the cell colour

的内容

但是,如果要在单元格中输入实际值,那么我不知道如何获取所需的背景色。

到目前为止我所拥有的:

import pandas as pd
#in the example, I have a list of office items, chairs and computers
names=['chair1','chair2','chair3','chair4','chair5','computer1','computer2','computer3','computer4','computer5']
#Each name has an assigned type. The type determines what the expectations are for the lifetime
inv_type=['furniture','furniture','furniture','furniture','furniture','electronics','electronics','electronics','electronics','electronics']
#The age of each item before breakdown is recorded here
inv_age=[2.2, 5, 7.3, 0.6, 4.3, 3.2, 1.7, 2.3, 2.2 ,0.9]

# a dictionary defines the minimum expected lifetime
expected_life={'furniture':4,'electronics':2}
# initialise the pass_fail list
inventory_pass_fail=[]

# cyle through the items and append 'pass' or 'fail' to the list depending on if the item 
#has reached the minimum expected age. 
for i in range(len(names)):
    if inv_age[i]>expected_life[inv_type[i]]:
        inventory_pass_fail.append('pass')
    else:
        inventory_pass_fail.append('fail')

#get names, type, and pass/fail list into one list for the excel sheet
final_list_report=list(zip(*[names,inv_type,inventory_pass_fail]))


df = pd.DataFrame(final_list_report,columns=['Name','Type','Pass/Fail'])

#define function that determines background colour
def color_code_by_text(val):
    if val=='N/A' or val=='pass':
        color='background-color: %s' % 'green'
    elif  val=='fail':
        color='background-color: %s' % 'red'
    else:
        color=''
    return color

#use style.applymap and the color_code_by_text function to colour background cells
styled = (df.style.applymap(color_code_by_text))
# and save the end result
styled.to_excel('inventory_report.xlsx', engine='openpyxl')

我尝试用实际值覆盖相同的文件。这可行,但是也消除了颜色。我想要的是这样的东西,其中颜色表示通过/失败状态,但单元格保留实际数字: The Pass/Fail column has the actual values, but the colour indicates whether it has passed or failed.

将感谢您的任何建议,谢谢!

1 个答案:

答案 0 :(得分:0)

好,我有事要做。基本上,我运行上面在问题中发布的代码以获取单元格背景色,然后使用openpyxl加载该文件并逐行编辑单元格值。这样可以保持背景色。

我在问题中的代码下方添加了下面显示的代码,这有效。

from openpyxl import load_workbook

#load the excel file that I just wrote
wb=load_workbook(filename='inventory_report.xlsx')

ws = wb.get_active_sheet()
#edit the sheet line by line inserting each value
for i in range(len(vals_list)):
    ws.cell(row=i+2,column=4).value = vals_list[i][2]

#and overwrite the previous file with the changes made
wb.save('inventory_report.xlsx')