Save the chart, then in Excel: Insert → Pictures → from file. Fastest for one-offs.
Covered in Module 8. Best for charts that should refresh when the underlying Excel data changes.
import pandas as pd
import matplotlib.pyplot as plt
from openpyxl import load_workbook
from openpyxl.drawing.image import Image
# Generate the chart
df = pd.read_csv("monthly.csv")
fig, ax = plt.subplots(figsize=(7, 3))
df.plot(x="month", y="revenue", ax=ax, marker="o")
plt.tight_layout()
fig.savefig("monthly.png", dpi=150)
plt.close(fig)
# Insert into the workbook
df.to_excel("report.xlsx", index=False, sheet_name="Data")
wb = load_workbook("report.xlsx")
ws = wb.create_sheet("Chart")
img = Image("monthly.png")
ws.add_image(img, "B2")
wb.save("report.xlsx")
One script. Reads a CSV. Writes a 2-sheet Excel: a Data sheet and a Charts sheet with three charts.
def make_chart(df, kind, filename, title):
fig, ax = plt.subplots(figsize=(7, 3))
df.plot(kind=kind, ax=ax, color="#217346")
ax.set_title(title)
plt.tight_layout()
fig.savefig(filename, dpi=150)
plt.close(fig)
Then call it three times and insert each via openpyxl.
=PY() chart that refreshes.add_image in code.Build a script that produces an Excel report with a Data sheet, a Bar Chart sheet, and a Line Chart sheet — all from one CSV input.