如何使用基于具有条件格式的熊猫数据框的 Python openpyxl 库更新 Excel 工作表中的特定单元格?

问题描述 投票:0回答:0

有人可以提供有关如何正确迭代数据框中的行并根据某些列的值更新 Excel 工作表中相应单元格的指导吗?您能否查看下面的示例代码和数据并提出改进建议?

示例数据:

  year            animal      branch  imp   val
0  2021              100           A  True  0.01
1  2021              101           B  True  0.02
2  2022              102           C  False 0.03
3  2022              103           D  True  0.04

我使用的代码:

import openpyxl
import pandas as pd
from openpyxl.styles import PatternFill

# Load the Excel file
book = openpyxl.load_workbook(folder+"input.xlsx")

def get_col_number(col, val, year):
    sheet = book[year]
    for column_cell in sheet.iter_cols(1, sheet.max_column):
        if column_cell[0].value == col:
            for cell in column_cell:
                if cell.value == val:
                    return cell

def get_row_number(rw, val, year):
    sheet = book[year]
    for row_cell in sheet.iter_rows(2, sheet.max_row):
        if row_cell[0].value == rw:
            for cell in row_cell:
                if cell.value == val:
                    return cell

# Create a dictionary to map True/False values to color values
color_map = {True: "FFFF00"}

# Iterate over the dataframe rows and update the corresponding cell in the Excel sheet
for index, row in data.iterrows():
    sheet = book[str(row["year"])]
    row_num = get_row_number(row["animal"],row["val"],str(row["year"]))
    col_num = get_col_number(row["bransh"],row["val"],str(row["year"]))

    cell = sheet.cell(row=row_num, column=col_num)
    if row["imp"]:
        #Fill the cell in yellow if data.imp
        cell.fill = PatternFill(start_color=color_map[row["imp"]], end_color=color_map[row["imp"]], fill_type="solid")

# Save the updated Excel file
book.save(folder+"output.xlsx")
python pandas openxlsx
© www.soinside.com 2019 - 2024. All rights reserved.