0

I have some custom code to write a custom object to excel using the xlsxwriter worksheet.write() method. This custom object doesn't fit as a dataframe so thats why I chose to write it myself, but I have additional data that is stored nicely as a dataframe that I want to save as a separate sheet to the same workbook that the xlsxwriter is writing to.

The issue I have is pandas is either overwriting the workbook that my custom code is creating or the pandas sheet is being lost. I confirmed it works correctly when saving them to separate documents but that's not what I want. I'm sure I can loop through the dataframe and print it myself but I feel like there has to be a better way.

My code looks something like this:

workbook = xlsxwriter.Workbook('Myexcel.xlsx')
with pd.ExcelWriter('Myexcel.xlsx', engine='xlsxwriter') as writer:
    df.to_excel(writer, sheet_name='DF_Sheet',index=False)

worksheet = workbook.add_worksheet('other_data')
# this is a simplified version of my custom printing function. I included this to show how I'm trying to combine the two types of data in the same file. 
for each in my_data:
    cell = 'A1'
    worksheet.write(cell, each)

kips
  • 17
  • 2
  • 8
  • 1
    See the following [Working with Pandas and XlsxWriter](https://xlsxwriter.readthedocs.io/working_with_pandas.html). – jmcnamara Apr 06 '23 at 20:51
  • Hi, this might help: [How to write to an existing excel file without overwriting data (using pandas)?](https://stackoverflow.com/questions/20219254/how-to-write-to-an-existing-excel-file-without-overwriting-data-using-pandas) – Laurent Apr 08 '23 at 06:17

0 Answers0