(1) двух вычисляемых полей в столбцах F и G и
(2) одного введенного вручную поле в столбце H.
- Если оба этих значения в строке рассчитаны как >=30, я хотел бы выделить соответствующую ячейку в столбец A.
- В качестве альтернативы, если значение в столбце H равно «Гарантийный ремонт», я хочу выделить соответствующую ячейку в столбце A в желтый.
Если это может помочь, ниже приведен пример моих данных:
Номер дела
Статус
Текущая дата
Дата создания
Дата изменения
Дни с момента создания
Дни с момента изменения
Тип
< /thead>
3051
Новый
[Сегодня ]
01 ноября 2024 г.
01 ноября 2024 г.
=DATEDIF(D2,C2 ,"d")
=DATEDIF(E2,C2,"d")
Гарантийное обслуживание
3048
Обслуживание запланировано
[Сегодня]
31 октября 2024 г.
01 ноября 2024 г.
=DATEDIF(D3,C3,"d")
=DATEDIF(E3,C3,"d")
Аппаратное обеспечение
...
2832
Обслуживание запланировано
[Сегодня]
20 августа 2024 г.
27 августа 2024 г.
=DATEDIF(D16,C16,"d")
=DATEDIF(E16,C16,"d")
Запрос клиента (перемещение)
В моем текущем коде я могу правильно выделить столбцы F и G на основе их расчетных значений.
Они должны быть светло-красными, если в ячейке больше 30.
Это выполняется с использованием условного форматирования:
from openpyxl import load_workbook
from openpyxl.styles import PatternFill, NamedStyle
from openpyxl.formatting.rule import CellIsRule
def format_xlsx(xlsx_file):
#Load the file and workbook
file_path = xlsx_file
workbook = load_workbook(file_path)
sheet = workbook.active
#Define the fills
light_red_fill = PatternFill(start_color="FFC7CE", end_color="FFC7CE", fill_type="solid")
dark_red_fill = PatternFill(start_color="8B0000", end_color="8B0000", fill_type="solid")
yellow_fill = PatternFill(start_color="FFFF00", end_color="FFFF00", fill_type="solid")
#Create conditional format rules for F and G:
sheet.conditional_formatting.add(
"F2:F1048576", # Apply to column F from row 2 onwards
CellIsRule(operator="greaterThanOrEqual", formula=["30"], fill=light_red_fill))
sheet.conditional_formatting.add(
"G2:G1048576", # Apply to column G from row 2 onwards
CellIsRule(operator="greaterThanOrEqual", formula=["30"], fill=light_red_fill))
workbook.save(file_path)
return xlsx_file
Однако, если я попытаюсь включить функцию, которая будет выделять ячейки в столбце A:
from openpyxl import load_workbook
from openpyxl.styles import PatternFill, NamedStyle
from openpyxl.formatting.rule import CellIsRule
def format_xlsx(xlsx_file): #Load the file and workbook file_path = xlsx_file workbook = load_workbook(file_path) sheet = workbook.active
#Define the fills
light_red_fill = PatternFill(start_color="FFC7CE", end_color="FFC7CE", fill_type="solid")
dark_red_fill = PatternFill(start_color="8B0000", end_color="8B0000", fill_type="solid")
yellow_fill = PatternFill(start_color="FFFF00", end_color="FFFF00", fill_type="solid")
#Create conditional format rules for F and G:
sheet.conditional_formatting.add(
"F2:F1048576", # Apply to column F from row 2 onwards
CellIsRule(operator="greaterThanOrEqual", formula=["30"], fill=light_red_fill))
sheet.conditional_formatting.add(
"G2:G1048576", # Apply to column G from row 2 onwards
CellIsRule(operator="greaterThanOrEqual", formula=["30"], fill=light_red_fill))
#Loop through each cell in columns F and G, ignoring the first row for headers.
red = "AND($F2>=30, $G2>=30)"
sheet.conditional_formatting.add(
"A2:A1048576", # Apply to column F from row 2 onwards
CellIsRule(formula=[red], fill=dark_red_fill))
workbook.save(file_path)
return xlsx_file
При открытии книги в Excel я получаю следующую ошибку:
"We found a problem with some content in 'testfile_04-Nov-2024.xlsx'.
Do you want us to try to recover as much as we can? If you trust the source of this workbook, click Yes."
После этого мне будет предложена возможность просмотра
Excel was able to open the file by repairing or removing the unreadable content.
и это сообщение об ошибке в документе Word:
Repair Result to testfile_04-Nov-2024.xlsx Errors were detected in file '/Users/llindgren/Downloads/testfile_04-Nov-2024.xlsx'
Removed Records: Conditional formatting from /xl/worksheets/sheet1.xml part
Я также пробовал использовать другую функцию для всего вышеперечисленного, но это не привело к выделению значений:
import openpyxl
from openpyxl.styles import PatternFill
# Load the Excel file
file_path = "your_file.xlsx"
workbook = openpyxl.load_workbook(file_path)
sheet = workbook.active
# Define the fill styles for highlighting
light_red_fill = PatternFill(start_color="FFC7CE", end_color="FFC7CE", fill_type="solid") # Light red for columns F and G
dark_red_fill = PatternFill(start_color="8B0000", end_color="8B0000", fill_type="solid") # Dark red for column A
# Loop through each row and check values in columns F and G
for row in range(2, sheet.max_row + 1): # Starting from row 2 to skip headers if they exist
cell_f = sheet[f"F{row}"]
cell_g = sheet[f"G{row}"]
# Check and highlight cells in F and G if their value >= 30
if cell_f.value is not None and isinstance(cell_f.value, (int, float)):
if cell_f.value >= 30:
cell_f.fill = light_red_fill # Highlight F
print(f"Highlighted F{row} with light red.") # Debug statement
if cell_g.value is not None and isinstance(cell_g.value, (int, float)):
if cell_g.value >= 30:
cell_g.fill = light_red_fill # Highlight G
print(f"Highlighted G{row} with light red.") # Debug statement
# Check if both F and G are >= 30, then apply dark red fill to column A
if (
cell_f.value is not None and cell_g.value is not None and
isinstance(cell_f.value, (int, float)) and isinstance(cell_g.value, (int, float)) and
cell_f.value >= 30 and cell_g.value >= 30
):
sheet[f"A{row}"].fill = dark_red_fill
print(f"Highlighted A{row} with dark red.") # Debug statement
# Save changes to the same file
workbook.save(file_path)
print("File saved successfully.")
Подробнее здесь: https://stackoverflow.com/questions/791 ... lated-valu
Мобильная версия