python - painting a cell in excel with condition using python
问题描述
I am creating an excel report that should give me a result of automatic tests. It should say if they failed/ passed. I have created the excel report from csv using this code:
import pandas as pd
import string
writer = pd.ExcelWriter("file.xlsx", engine="xlsxwriter")
df = pd.read_csv("K:\\results.csv")
df.to_excel(writer, sheet_name=os.path.basename("K:\\results.csv"))
# skip 2 rows
df.to_excel(writer, sheet_name='Sheet1', startrow=2, header=False, index=False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']
# Add a header format.
header_format = workbook.add_format({
'bold': True,
'fg_color': '#ffcccc',
'border': 1})
# create dictionary for map length of columns
d = dict(zip(range(25), string.ascii_uppercase))
print (d)
max_len = d[len(df.columns) - 1]
print(max_len)
# C
# dynamically set merged columns in first row
worksheet.merge_range('A1:' + max_len + '1', 'This Sheet is for Personal Details')
for col_num, value in enumerate(df.columns.values):
# write to second row
worksheet.write(1, col_num, value, header_format)
column_len = df[value].astype(str).str.len().max()
column_len = max(column_len, len(value)) + 3
worksheet.set_column(col_num, col_num, column_len)
writer.save()
Now, if i have a cell that has the word" success" in it, i want to color it green, and if i have a cell in the excel which says "fail" in it i want to color it red. How can i access a specific cell in the excel file with the condition of whats written in it? Thanks.
解决方案
您可以为此使用条件格式:
import pandas as pd
# Create a Pandas dataframe from some data.
df = pd.DataFrame({'Data': ['success', 'bar', 'fail', 'foo', 'success']})
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_conditional.xlsx', engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')
# Get the xlsxwriter workbook and worksheet objects.
workbook = writer.book
worksheet = writer.sheets['Sheet1']
# Add a format for fail. Light red fill with dark red text.
fail_format = workbook.add_format({'bg_color': '#FFC7CE',
'font_color': '#9C0006'})
# Add a format for pass. Green fill with dark green text.
pass_format = workbook.add_format({'bg_color': '#C6EFCE',
'font_color': '#006100'})
# Apply conditional formats to the cell range.
worksheet.conditional_format('B2:B6', {'type': 'text',
'criteria': 'containing',
'value': 'fail',
'format': fail_format})
worksheet.conditional_format('B2:B6', {'type': 'text',
'criteria': 'containing',
'value': 'success',
'format': pass_format})
# Close the Pandas Excel writer and output the Excel file.
writer.save()
输出:
请参阅有关使用条件格式的 XlsxWriter 文档。请注意,您还可以使用数字(行,列)范围而不是A1:D4
范围,请参阅conditional_format()。
推荐阅读
- wcf - 无法在 ASP.NET Core 5.0 下的 IIS 中托管 CoreWcf
- angular - 我想将日期转换为 dd-mm-yyyy
- python - 尝试从 gstreamer appsink 获取 numpy 图像导致缓冲区太小错误
- node.js - 是否有一种直接的方式来验证 Joi 中的多个条件
- python - SIFT 无法关联清晰相关的图像
- timer - 我想使用两个不同的时间通过单个 UART 发送和接收数据
- python - 如何使用 python 将特定的 xml 标签移动到新的 xml 文件?
- java - 使用 telnet 连接通过 java 代码向 Digi 发送 Ctrl+Break
- windows - 不能有一个零长度的 USB“串行”字符串描述符?
- reactjs - mui DataGrid 滚动条在 columnHeader 上不起作用