|
| 1 | +import pandas as pd |
| 2 | +from openpyxl import load_workbook |
| 3 | +from openpyxl.styles import Font |
| 4 | +from openpyxl.chart import BarChart, Reference |
| 5 | + |
| 6 | +# Load data |
| 7 | +df = pd.read_excel('https://github.com/datagy/pivot_table_pandas/raw/master/sample_pivot.xlsx', parse_dates=['Date']) |
| 8 | +df['Date'] = pd.to_datetime(df['Date']) |
| 9 | +print(df.head()) |
| 10 | + |
| 11 | +# Summary table for East region |
| 12 | +filtered = df[df['Region'] == 'East'] |
| 13 | +quaterly_sales = pd.pivot_table(filtered, index=['Date'], columns='Type', values='Sales', aggfunc='sum') |
| 14 | +print('Quaterly Sales Pivot Table') |
| 15 | +print(quaterly_sales.head()) |
| 16 | + |
| 17 | +# Load data into Excel file |
| 18 | +filepath = 'reporting_file.xlsx' |
| 19 | +quaterly_sales.to_excel(filepath, sheet_name='Quaterly Sales', startrow=3) |
| 20 | + |
| 21 | +# Making report prettier |
| 22 | +wb = load_workbook(filepath) |
| 23 | +sheet1 = wb['Quaterly Sales'] |
| 24 | + |
| 25 | +sheet1['A1'] = 'Quaterly Sales' |
| 26 | +sheet1['A2'] = 'datagy.io' |
| 27 | +sheet1['A4'] = 'Quarter' |
| 28 | + |
| 29 | +sheet1['A1'].style = 'Title' |
| 30 | +sheet1['A2'].style = 'Headline 2' |
| 31 | + |
| 32 | +for i in range(5, 9): |
| 33 | + sheet1[f'B{i}'].style = 'Currency' |
| 34 | + sheet1[f'C{i}'].style = 'Currency' |
| 35 | + sheet1[f'D{i}'].style = 'Currency' |
| 36 | + |
| 37 | +bar_chart = BarChart() |
| 38 | +data = Reference(sheet1, min_col=2, max_col=4, min_row=4, max_row=8) |
| 39 | +categories = Reference(sheet1, min_col=1, max_col=1, min_row=5, max_row=8) |
| 40 | +bar_chart.add_data(data, titles_from_data=True) |
| 41 | +bar_chart.set_categories(categories) |
| 42 | +sheet1.add_chart(bar_chart, "F4") |
| 43 | + |
| 44 | +bar_chart.title = 'Sales by Type' |
| 45 | +bar_chart.style = 3 |
| 46 | +wb.save(filename=filepath) |
0 commit comments