44"""
55from __future__ import print_function
66import pandas as pd
7+ from xlsxwriter .utility import xl_rowcol_to_cell
78
89
9- def format_excel (writer ):
10+ def format_excel (writer , df_size ):
1011 """ Add Excel specific formatting to the workbook
12+ df_size is a tuple representing the size of the dataframe - typically called
13+ by df.shape -> (20,3)
1114 """
1215 # Get the workbook and the summary sheet so we can add the formatting
1316 workbook = writer .book
@@ -16,15 +19,20 @@ def format_excel(writer):
1619 money_fmt = workbook .add_format ({'num_format' : 42 , 'align' : 'center' })
1720 worksheet .set_column ('A:A' , 20 )
1821 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' })
22+ # Add 1 to row so we can include a total
23+ # subtract 1 from the column to handle because we don't care about index
24+ table_end = xl_rowcol_to_cell (df_size [0 ] + 1 , df_size [1 ] - 1 )
25+ # This assumes we start in the left hand corner
26+ table_range = 'A1:{}' .format (table_end )
27+ worksheet .add_table (table_range , {'columns' : [{'header' : 'account' ,
28+ 'total_string' : 'Total' },
29+ {'header' : 'Total Sales' ,
30+ 'total_function' : 'sum' },
31+ {'header' : 'Average Sales' ,
32+ 'total_function' : 'average' }],
33+ 'autofilter' : False ,
34+ 'total_row' : True ,
35+ 'style' : 'Table Style Medium 20' })
2836
2937
3038if __name__ == "__main__" :
@@ -34,5 +42,5 @@ def format_excel(writer):
3442 sales_summary .reset_index (inplace = True )
3543 writer = pd .ExcelWriter ('sales_summary.xlsx' , engine = 'xlsxwriter' )
3644 sales_summary .to_excel (writer , 'summary' , index = False )
37- format_excel (writer )
45+ format_excel (writer , sales_summary . shape )
3846 writer .save ()
0 commit comments