Openpyxl Development Tutorials, Guides & Insights

Unlock 1+ expert-curated openpyxl tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your openpyxl skills on DeveloperBreeze.

Automating Excel Reports with Python and OpenPyXL

Tutorial December 10, 2024
python

Create a summary sheet to show the total sales for all products and the highest-selling product.

# Add a new sheet for the summary
summary = workbook.create_sheet('Summary')

# Calculate total sales for all products
total_sales = sum(sheet.cell(row=row, column=5).value for row in range(2, sheet.max_row + 1))

# Find the highest-selling product
highest_sales = max(sheet.cell(row=row, column=5).value for row in range(2, sheet.max_row + 1))
highest_product = None
for row in range(2, sheet.max_row + 1):
    if sheet.cell(row=row, column=5).value == highest_sales:
        highest_product = sheet.cell(row=row, column=1).value
        break

# Write summary data
summary.cell(row=1, column=1, value="Total Sales")
summary.cell(row=1, column=2, value=total_sales)
summary.cell(row=2, column=1, value="Highest-Selling Product")
summary.cell(row=2, column=2, value=highest_product)

# Save the updated workbook
workbook.save('sales_report_with_summary.xlsx')