python - Python openpyxl空白单元格条件格式
问题描述
我在格式化空白单元格时遇到问题。我的代码是
import setting_prices
import pandas as pd
from openpyxl import Workbook, load_workbook
from openpyxl.styles import Color, PatternFill, Font, Border
from openpyxl.styles.differential import DifferentialStyle
from openpyxl.formatting.rule import ColorScaleRule, CellIsRule, FormulaRule
import os
from datetime import datetime
def load_file_apply_format():
wb = load_workbook(filename)
writer = pd.ExcelWriter(filename, engine='openpyxl')
writer.book = wb
prices.to_excel(writer, sheet_name=today_as_str)
ws = wb[today_as_str]
redFill = PatternFill(start_color='EE1111',
end_color='EE1111',
fill_type='solid')
# whiteFill = PatternFill(start_color='FFFFFF',
# end_color='FFFFFF',
# fill_type='solid')
ws.conditional_formatting.add('B2:H99',
CellIsRule(operator='lessThan',
formula=['$I2'],
stopIfTrue=False, fill=redFill))
writer.save()
prices = setting_prices.df
today_as_str = datetime.strftime(datetime.now(), ' %d_%m_%y')
desktop_path = os.path.expanduser("~/Desktop")
filename = 'price_check.xlsx'
if os.path.exists(filename):
load_file_apply_format()
else:
prices.to_excel(filename, sheet_name=today_as_str)
load_file_apply_format()
我的公式工作得很好,但 excel 将空白单元格视为 0,因此它们总是小于第一列,并格式化它们。我想跳过空白单元格,或者将它们格式化为看起来像常规单元格。
我已经尝试了论坛的几乎所有建议,但似乎我无法修复它。
请给我一些建议。
@Greg 使用答案:
ws.conditional_formatting.add('B2:H99',
CellIsRule(operator='between',
formula=['1', '$I2'],
stopIfTrue=False, fill=redFill))
导致形成我想避免的 == 到 'I' 列的单元格。如果“I”列中的单元格为空,“between”也将格式设置为所有空白单元格。
例如:productA 的所有单元格必须采用默认格式,因为它们等于“I”列中的单元格。对于productB
唯一的格式化单元格必须是G3
因为低于 then I3
。的所有单元格都productC
必须采用默认格式,因为 I 中的单元格为空。
我想,如果我将我的格式化代码用于 lessThen,那么空白单元格的另一个公式就可以完成这项工作。但我无法让它工作。
解决方案
我设法用 try/error 方法解决了我的问题。我将在这里发布我的解决方案,希望有人会发现它有用。最终结果是由:
- 将行中的所有单元格放置到列表中
- 将列表中的所有值与所需的值进行比较
- 如果单元格较低-> 应用格式化
最终代码是:
import ...
def apply_format_to_cell(cell):
"""
Set background and font color For the current cell
"""
ft = Font(color="FF0000")
fill_black = PatternFill(bgColor="FFC7CE", fill_type="solid")
cell.font = ft
cell.fill = fill_black
return cell
def open_existing_file(file_name):
"""
open an existing file to format cell
which is meeting a condition
"""
wb = load_workbook(file_name)
writer = pd.ExcelWriter(file_name, engine='openpyxl')
writer.book = wb
prices.to_excel(writer, sheet_name=today_as_str)
ws = wb[today_as_str]
for row in ws.iter_rows(2, ws.max_row, 2):
"""
1st parameter says to start from 2 row
2nd parameter stands for -> till the last row with data.
3th parameter says start from 2 COLUMN.
In this case this is B2
"""
cells_in_row = [] # making a list of cells which we will compare
for cells in row:
cells_in_row.append(cells)
for cell in cells_in_row:
if cell.value is not None and type(cell.value) is not str \
and cells_in_row[-1].value is not None and type(cells_in_row[-1].value) is not str:
"""
Checks if the cell value is not Empty or str ( '' ).
"""
if cell.value < cells_in_row[-1].value:
apply_format_to_cell(cell)
if wb[f'{today_as_str + "1"}']:
"""
For the first run only!
Because: prices.to_excel(writer, sheet_name=today_as_str) will make again sheet
with the same name -> Excel will put '1' at the end of name 'Sheet_name' > 'Sheet_name1'
This if will delete this unwanted sheet!
"""
del wb[f'{today_as_str + "1"}']
writer.save()
prices = setting_prices.df # import df with prices
today_as_str = datetime.strftime(datetime.now(), ' %d_%m_%y')
desktop_path = os.path.expanduser("~/Desktop")
filename = 'price_check.xlsx'
if os.path.exists(filename):
open_existing_file(filename)
else:
prices.to_excel(filename, sheet_name=today_as_str)
open_existing_file(filename)
推荐阅读
- sql - SQL - 基于时间线的查询
- bluetooth - 从哪里获得适用于 Raspberry Pi 的 Bluetooth/Bluetooth.h?
- angular - cdkVirtualFor 不显示任何内容
- python - 如何将 React 连接到 Django?
- r - R - 闪亮矩阵上二元运算符的非数字参数
- arrays - 如何将元素(列表)添加到 JSON 中。扑
- django - ModuleNotFoundError:没有在 django 中命名的模块
- vb.net - 查询表达式 '[void]'=' 中缺少语法错误运算符
- gitlab - GitLab 运行器使用 shell 执行器失败:作业失败(系统故障):准备环境:
- c++ - 具有非类型参数的类的非类型参数成员函数的部分特化