Pandas: save data to open workbook

I have an open workbook with data written to. How do I add sheets to record the content of a frame?

import xlsxwriter
import pandas as pd

workbook = xlsxwriter.Workbook('test.xlsx')
sheet1 = workbook.add_worksheet(name='sheet1')
sheet1.write(0, 0, 'test')
df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': ['aa', 'bb', 'cc', 'dd']})
# write df somehow to next sheet. I usually use df.to_excel(filename, engine='xlsxwriter'), but this will create a new file
workbook.close()

      

+3


source to share


1 answer


As you understood in your comments, you cannot pass the XlsxWriter pandas workbook object to_excel()

.

As a workaround, you can create a worksheet with an empty dataframe and then access XlsxWriter objects and worksheet pages. Then you can add additional sheets through the pandas interface.

Here's a small working example based on your code:



import pandas as pd

# Create an pandas excel writer based on xlsxwriter.
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')

# Create a worksheet with an empty dataframe so the sheet is empty.
df = pd.DataFrame()
df.to_excel(writer, sheet_name='Sheet1')

# Access the underlying xlsxwriter worksheet and write to it.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']
worksheet.write(0, 0, 'test')

# Create another dataframe with data.
df = pd.DataFrame({'a': [1, 2, 3, 4],
                   'b': ['aa', 'bb', 'cc', 'dd']})

# Write the dataframe to another worksheet.
df.to_excel(writer, sheet_name='Sheet2')

writer.save()

      

See also Working with Python pandas and XlsxWriter .

+2


source







All Articles