简体   繁体   English

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

[英]background cell colour control in excel using python

I would like to be able to control the background cell colour in excel. 我希望能够在Excel中控制背景单元格的颜色。 I have largish amounts of data, and I need to determine if the data meets the expectations or not. 我的数据量很大,因此需要确定数据是否符合预期。 This I can do already with Python. 我已经可以使用Python做到这一点。 However, I would like to display this data in excel, and to make it easier to read, I would like to colour cells according to if the data is good or not. 但是,我想在excel中显示此数据,并使其更易于阅读,我想根据数据的好坏为单元格上色。

I have already used style.applymap to assign colour to a cell based on specific cell values. 我已经使用style.applymap根据特定的单元格值将颜色分配给单元格。 For instance, if the cell says 'fail' then I can colour it red. 例如,如果单元格显示“失败”,那么我可以将其涂成红色。

So if I go through the data and make a new 'pass'/'fail' list and enter these values into the excel document, I can get what I want in terms of colour. 因此,如果我浏览数据并创建一个新的“通过” /“失败”列表,然后将这些值输入到excel文档中,就可以得到我想要的颜色。 This code is shown below, and I can get something that looks like this 此代码如下所示,我可以得到类似以下内容的代码 “通过/失败”列的文本为“通过”或“失败”,用于定义单元格颜色

However, if I want to enter the actual values into the cells, then I have no idea how to get the background colours I want. 但是,如果要在单元格中输入实际值,则不知道如何获取所需的背景色。

What I have so far: 到目前为止,我有:

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')

I have tried overwriting the same file with the actual values. 我尝试用实际值覆盖相同的文件。 This works, but it gets rid of the colour as well. 这可行,但是也消除了颜色。 What I'd like is something like this, where the colour indicates the pass/fail status, but the cell holds the actual number: 我想要的是这样的东西,其中颜色表示通过/失败状态,但单元格保留实际数字: “通过/失败”列具有实际值,但是颜色指示其通过还是失败。

Would appreciate any advice, thanks! 希望得到任何建议,谢谢!

Ok, I got something to work. 好吧,我有事要干。 Basically, I run the code that I posted above in the question to get the cell background colours, then I use openpyxl to load that file and edit the cell values line by line. 基本上,我运行上面在问题中发布的代码以获取单元格背景色,然后使用openpyxl加载该文件并逐行编辑单元格值。 This keeps the background colour. 这样可以保持背景色。

I added the code shown below under the code in the question, and this works. 我在问题中的代码下添加了下面显示的代码,并且可以正常工作。

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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