python
"""
Automated Excel Report Generator using openpyxl.
This script generates a sample sales report with:
- Formatted headers
- Sample sales data with calculated totals
- Grand total formula
- Basic styling (bold headers, colors, borders, alignment)
- Auto-adjusted column widths
- A simple chart (line chart for totals)
Requirements:
- pip install openpyxl
Run the script to generate 'sales_report.xlsx'.
"""
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Border, Side, Alignment
from openpyxl.chart import LineChart, Reference
from openpyxl.chart.axis import DateAxis
import datetime
def create_sales_report():
# Create a new workbook and select the active sheet
wb = Workbook()
ws = wb.active
ws.title = "Sales Report"
# Define headers
headers = ['Date', 'Product', 'Quantity', 'Unit Price ($)', 'Total ($)']
header_font = Font(bold=True, color="FFFFFF")
header_fill = PatternFill(start_color="366092", end_color="366092", fill_type="solid")
center_align = Alignment(horizontal="center", vertical="center")
# Add headers to row 1
for col, header in enumerate(headers, 1):
cell = ws.cell(row=1, column=col, value=header)
cell.font = header_font
cell.fill = header_fill
cell.alignment = center_align
# Sample data: Generate 10 days of sales data programmatically
start_date = datetime.date(2023, 10, 1)
products = ['Widget A', 'Widget B', 'Gadget X', 'Tool Y']
data = []
for i in range(10):
date = start_date + datetime.timedelta(days=i)
product = products[i % len(products)]
quantity = 5 + (i * 2) # Increasing quantity
unit_price = round(20 + (i * 2.5), 2) # Increasing price
data.append((date, product, quantity, unit_price))
# Add data starting from row 2
thin_border = Border(
left=Side(style='thin'),
right=Side(style='thin'),
top=Side(style='thin'),
bottom=Side(style='thin')
)
currency_fill = PatternFill(start_color="E2EFDA", end_color="E2EFDA", fill_type="solid")
for row_idx, row_data in enumerate(data, 2):
# Date, Product, Quantity, Unit Price
ws.cell(row=row_idx, column=1, value=row_data[0])
ws.cell(row=row_idx, column=2, value=row_data[1])
ws.cell(row=row_idx, column=3, value=row_data[2])
cell_price = ws.cell(row=row_idx, column=4, value=row_data[3])
cell_price.fill = currency_fill
cell_price.number_format = '$#,##0.00'
# Total formula: =C[row]*D[row]
total_cell = ws.cell(row=row_idx, column=5)
total_cell.value = f'=C{row_idx}*D{row_idx}'
total_cell.number_format = '$#,##0.00'
total_cell.fill = currency_fill
# Apply borders to data rows
for col in range(1, 6):
ws.cell(row=row_idx, column=col).border = thin_border
# Grand Total in row 13 (after 10 data rows + 1 header + 1 spacer)
ws.cell(row=12, column=5, value="Grand Total")
grand_total_cell = ws.cell(row=13, column=5)
grand_total_cell.value = f'=SUM(E2:E11)'
grand_total_cell.font = Font(bold=True)
grand_total_cell.number_format = '$#,##0.00'
grand_total_cell.fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
grand_total_cell.font = Font(color="FFFFFF")
# Auto-adjust column widths
column_widths = {'A': 12, 'B': 15, 'C': 10, 'D': 15, 'E': 15}
for col, width in column_widths.items():
ws.column_dimensions[col].width = width
# Create a line chart for Total Sales over Date
chart = LineChart()
chart.title = "Sales Trend"
chart.style = 10
chart.x_axis.title = 'Date'
chart.y_axis.title = 'Total Sales ($)'
chart.height = 10
chart.width = 15
# Data for chart: Dates (cat axis), Totals (values)
dates = Reference(ws, min_col=1, min_row=2, max_row=11)
totals = Reference(ws, min_col=5, min_row=2, max_row=11)
chart.add_data(totals, titles_from_data=True)
chart.set_categories(dates)
# Position chart
ws.add_chart(chart, "G2")
# Freeze the header row
ws.freeze_panes = "A2"
# Save the workbook
filename = "sales_report.xlsx"
wb.save(filename)
print(f"Report generated successfully: {filename}")
if __name__ == "__main__":
create_sales_report()