1

I have two sheets in my excel workbook. The first sheet contains the data used to make the pivot table, and the second sheet as you can see I create in this section of the code. I would like my pivot table to be drawn into the new sheet that I created (worksheet2).

When I run my code, my excel file contains my data sheet, and then an empty sheet called 'Pivot Table'. How can I get my pivot table into the 'Pivot Table' sheet? This might be an extremely simple question, but i've just started working with pandas today. My pivot table does get created properly. I have printed it to test it and make sure of it.

Thanks.

excel = pd.ExcelFile(filename)
df = pd.read_excel(filename, usecols=['Product Description', 'Supervisor'])

table1 = df[['Product Description', 'Supervisor']].pivot_table(index='Supervisor', columns='Product Description', aggfunc=len, fill_value=0, margins=True, margins_name='Grand Total')

worksheet2 = workbook.create_sheet()
worksheet2.title = 'Pivot Table'
worksheet2 = workbook.active

writer = pd.ExcelWriter(filename, engine='xlsxwriter')
table1.to_excel(writer, worksheet2.title )

writer.save()
workbook.save(filename)
Harrison
  • 5,095
  • 7
  • 40
  • 60

1 Answers1

2

you can do it this way:

df = pd.read_excel(filename, usecols=['Product Description', 'Supervisor'])

table1 = df.pivot_table(index='Supervisor', columns='Product Description', aggfunc=len, fill_value=0, margins=True, margins_name='Grand Total')

writer = pd.ExcelWriter(filename, engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
table1.to_excel(writer, 'Pivot Table')
writer.save()
Community
  • 1
  • 1
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419