|
| 1 | +""" |
| 2 | +See http://pbpython.com/advanced-excel-workbooks.html for details on this script |
| 3 | +
|
| 4 | +""" |
| 5 | +from __future__ import print_function |
| 6 | +import pandas as pd |
| 7 | + |
| 8 | + |
| 9 | +def format_excel(writer): |
| 10 | + """ Add Excel specific formatting to the workbook |
| 11 | + """ |
| 12 | + # Get the workbook and the summary sheet so we can add the formatting |
| 13 | + workbook = writer.book |
| 14 | + worksheet = writer.sheets['summary'] |
| 15 | + # Add currency formatting and apply it |
| 16 | + money_fmt = workbook.add_format({'num_format': 42, 'align': 'center'}) |
| 17 | + worksheet.set_column('A:A', 20) |
| 18 | + worksheet.set_column('B:C', 15, money_fmt) |
| 19 | + worksheet.add_table('A1:C22', {'columns': [{'header': 'account', |
| 20 | + 'total_string': 'Total'}, |
| 21 | + {'header': 'Total Sales', |
| 22 | + 'total_function': 'sum'}, |
| 23 | + {'header': 'Average Sales', |
| 24 | + 'total_function': 'average'}], |
| 25 | + 'autofilter': False, |
| 26 | + 'total_row': True, |
| 27 | + 'style': 'Table Style Medium 20'}) |
| 28 | + |
| 29 | + |
| 30 | +if __name__ == "__main__": |
| 31 | + sales_df = pd.read_excel('https://github.com/chris1610/pbpython/blob/master/data/sample-salesv3.xlsx?raw=true') |
| 32 | + sales_summary = sales_df.groupby(['name'])['ext price'].agg(['sum', 'mean']) |
| 33 | + # Reset the index for consistency when saving in Excel |
| 34 | + sales_summary.reset_index(inplace=True) |
| 35 | + writer = pd.ExcelWriter('sales_summary.xlsx', engine='xlsxwriter') |
| 36 | + sales_summary.to_excel(writer, 'summary', index=False) |
| 37 | + format_excel(writer) |
| 38 | + writer.save() |
0 commit comments