本文介绍了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,因此它们始终小于第I列,并对它们进行格式化。我想跳过空白单元格,或将其格式设置为与常规单元格类似。
我几乎尝试了论坛中的所有建议,但似乎无法解决它。
请给我一些建议。
@Greg使用答案:
ws.conditional_formatting.add('B2:H99',
CellIsRule(operator='between',
formula=['1', '$I2'],
stopIfTrue=False, fill=redFill))
导致形成从==到‘i’列的单元格,这是我想要避免的。如果"I"列中的单元格为空,则"BETWING"表示将格式设置为所有空白单元格。
例如:ProductA的所有单元格必须为默认格式,因为它们等于列‘i’中的单元格。对于productB
,唯一带格式的单元格必须是G3
,因为小于I3
。productC
的所有单元格都必须为默认格式,因为i中的单元格为空。
我想,如果我用我的格式代码来表示less Then,而用另一个公式表示空格,就可以完成这项工作。但我没能让它起作用。
推荐答案
我设法用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)
最终结果示例: 这篇关于Python OpenPYXL空白单元格条件格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!