Skip to content

Commit 43156b6

Browse files
committed
Advanced excel code example
1 parent 6e55fad commit 43156b6

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

code/advanced_excel.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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

Comments
 (0)