繁体   English   中英

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

[英]background cell colour control in excel using python

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

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

因此,如果我浏览数据并创建一个新的“通过” /“失败”列表,然后将这些值输入到excel文档中,就可以得到我想要的颜色。 此代码如下所示,我可以得到类似以下内容的代码 “通过/失败”列的文本为“通过”或“失败”,用于定义单元格颜色

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

到目前为止,我有:

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

我尝试用实际值覆盖相同的文件。 这可行,但是也消除了颜色。 我想要的是这样的东西,其中颜色表示通过/失败状态,但单元格保留实际数字: “通过/失败”列具有实际值,但是颜色指示其通过还是失败。

希望得到任何建议,谢谢!

好吧,我有事要干。 基本上,我运行上面在问题中发布的代码以获取单元格背景色,然后使用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')

暂无
暂无

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

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