[英]How to change font color of string in excel cell with condition "Greater than or equal to" using python?
I have an excel file with data stored as strings in different columns.我有一个 excel 文件,其中的数据以字符串形式存储在不同的列中。 I want to apply the condition >= and change the text color to red if the condition is met in that cell of the column without changing the header background color.
如果在列的该单元格中满足条件,我想应用条件 >= 并将文本颜色更改为红色,而不更改标题背景颜色。
Data: https://1drv.ms/x/s!ArCp0UbnlDouglYGkM83sQtckagM?e=e5nUgn数据: https : //1drv.ms/x/s!ArCp0UbnlDouglYGkM83sQtckagM?e=e5nUgn
Condition: If any value in column Qt._For_1s is greater than or equal to 900.0 then the font color of that specific value should turn into Red (without messing with the header colors) else can either be green or stay the same black with white background and saved as xls file.条件:如果Qt._For_1s列中的任何值大于或等于 900.0,则该特定值的字体颜色应变为红色(不会弄乱标题颜色),否则可以是绿色或保持黑色与白色背景相同并保存为 xls 文件。
Note: These column values are saved as strings because they are needed like that.注意:这些列值保存为字符串,因为它们是这样需要的。 I have tried several conditional formats but could not solve my specific problem.
我尝试了几种条件格式,但无法解决我的具体问题。
def highlight_Qt(row):
ret=["" for _ in row.index]
if (row.Qt._For_1s) >= str(900.0): # also tried without str() no results
ret[row.index.get_loc("Qt._For_1s")]="background-color: Red"
return ret
data.style.apply(highlight_Qt, axis=1).to_excel("Data.xlsx", engine='openpyxl')
This messes up the header color and not giving the required results.这弄乱了标题颜色并且没有给出所需的结果。 I am looking this up in StackOverflow posts over the last 5 days but could not find any post related to this specific condition.
我在过去 5 天内在 StackOverflow 帖子中查找此内容,但找不到与此特定条件相关的任何帖子。
One way to do it would be to open your file with openpyxl and format it一种方法是使用 openpyxl 打开文件并对其进行格式化
from openpyxl.styles import Font
from openpyxl import Workbook
# Open the workbook
from openpyxl import load_workbook
wb = load_workbook('file_name.xlsx')
ws = wb.active
# Get the columns name
ColNames = {}
Current = 0
for COL in ws.iter_cols(1, ws.max_column):
ColNames[COL[0].value] = Current
Current += 1
## Set the font color
ft = Font(color="00FF0000")
## Acces the cells
for row in ws.iter_rows():
cell = row[ColNames['Qt._For_1s']]
try:
if int(cell.value) > 900:
cell.font = ft
except:
pass
wb.save("styled.xlsx")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.