How to auto-define excel sheet name using XlsxWriter?

Viewed 2311

Is there a way to name an excel worksheet dynamically from the value of a cell in a pandas dataframe?

Here is the what I have:

#dataframe cell i want to work as sheet name is here
df_storename = df_store.loc[1, 'Store']

writer = pd.ExcelWriter('payroll.xlsx', engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
df_store.to_excel(writer, sheet_name=df_storename)

workbook = writer.book
worksheet1 = writer.sheets[df_storename]
worksheet2 = workbook.add_worksheet('One-on-One')

chart = workbook.add_chart({'type': 'column'})
chart1 = workbook.add_chart({'type': 'column'})

chart.add_series({'values': '=df_storename!$F$0:$F$9', 'name': 
'Service Sales', 'categories':
    '=df_storename!$C$2:$C$11'})
chart1.add_series({'values': '=df_storename!$P$0:$P$9', 
'name': 'Paid Back Bar %', 'categories':
    '=df_storename!$C$2:$C$11'})
1 Answers

The best way to do this is to use the list syntax in add_series() rather than the A1:C8 range syntax. For example:

import pandas as pd

# Create a Pandas dataframe from some data.
df_store = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
df_storename = 'My Storename'

writer = pd.ExcelWriter('payroll.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df_store.to_excel(writer, sheet_name=df_storename)

workbook = writer.book
worksheet1 = writer.sheets[df_storename]
worksheet2 = workbook.add_worksheet('One-on-One')

chart = workbook.add_chart({'type': 'column'})


chart.add_series({'name': 'Service Sales',
                  'categories': [df_storename, 1, 0, 7, 0],
                  'values':     [df_storename, 1, 1, 7, 1]})

worksheet2.insert_chart('D2', chart)

writer.save()

Output:

enter image description here

This way you can set the range of cells to be plotted using the size of the dataframe. For a more realistic example see the XlsxWriter Pandas chart examples.

Related