DEV Community

Cover image for How To Automate Highliting Maximum Values in Excel Charts Using Python
Sona
Sona

Posted on

How To Automate Highliting Maximum Values in Excel Charts Using Python

Imagine you have a huge Excel sheet with lots of numbers, and you want to find the biggest number in the whole sheet. Doing this manually would take a lot of time and effort, right? But what if I told you that you can use Python, a programming language, to do this automatically?

In this tutorial, we’ll learn how to automate the process of finding the maximum value in Excel charts using Python. This means that Python will do all the work for us, saving us time and making our lives easier.

We’ll use a library called openpyxl to work with Excel files in Python. With openpyxl, we can load the Excel file, read the data, and find the maximum value. Then, we’ll use this information to highlight the maximum value in the Excel chart.

By the end of this tutorial, you’ll have a Python script that can quickly and efficiently find the maximum value in Excel charts, saving you time and effort. So, let’s dive in and learn how to automate highlighting maximum values in Excel charts using Python!

Create a .py extension file in Python and start with the code

from openpyxl import load_workbook
from openpyxl.chart import BarChart, Reference
from openpyxl.styles import PatternFill
from openpyxl.utils.dataframe import dataframe_to_rows
import pandas as pd

# Load the Excel file
file_path = "Indian_employee_names.xlsx"
wb = load_workbook(filename=file_path)
ws = wb.active

# Assuming data is in columns A, B, and C, change as needed
data = pd.DataFrame(ws.iter_rows(values_only=True), columns=["Employee", "Age", "Salary"])

# Convert "Salary" column to numeric
data["Salary"] = pd.to_numeric(data["Salary"], errors='coerce')

# Create a chart
chart = BarChart()
chart.type = "col"
chart.style = 10
chart.title = "Chart with Highlighted Maximum Values"
chart.x_axis.title = "Employee"
chart.y_axis.title = "Salary"

# Add data to the chart
rows = dataframe_to_rows(data, index=False, header=True)
chart.add_data(Reference(ws, min_col=3, min_row=1, max_row=len(data), max_col=3), titles_from_data=True)
chart.set_categories(Reference(ws, min_col=1, min_row=2, max_row=len(data)+1))

# Add the chart to the worksheet
ws.add_chart(chart, "E2")

# Identify and highlight maximum values
max_salary = data["Salary"].max()
max_values = data.loc[data["Salary"] == max_salary]
for idx, row in max_values.iterrows():
    cell = ws.cell(row=idx+2, column=3)  # Assuming Salary is in column C
    cell.fill = PatternFill(start_color="FFFF00", end_color="FFFF00", fill_type="solid")

# Save the workbook
wb.save("highlighted_chart.xlsx")
Enter fullscreen mode Exit fullscreen mode

Read More

Top comments (0)