Search code examples
pythonpandaspandas.excelwriter

Why I can't add a figure to separate sheet in Excel Workbook?


I need to save data and corresponding figure in separate excel sheets.

writer = pd.ExcelWriter('Fiber Forecast.xlsx', engine = 'xlsxwriter')
fiber_forecast_future.to_excel(writer,sheet_name='Future', index=True)
worksheet = writer.sheets['New Sheet']
worksheet.insert_image('C2','India Fiber Price.png')
workbook.save()

But when I tried this, adding 'New Sheet' doesn't work.I need to add the image to that worksheet.I'm having this error.

 ---------------------------------------------------------------------------
    KeyError                                  Traceback (most recent call last)
    <ipython-input-11-950dc62ed281> in <module>
        109 writer = pd.ExcelWriter('Fiber Forecast.xlsx', engine = 'xlsxwriter')
        110 fiber_forecast_future.to_excel(writer,sheet_name='Future', index=True)
    --> 111 worksheet = writer.sheets['New Sheet']
        112 #worksheet.insert_image('C2','India Fiber Price.png')
        113 workbook.save()
    
    KeyError: 'New Sheet'

Solution

  • You can use

    writer.book.add_worksheet("New Sheet") 
    

    instead. There is more information regarding this method and the workbook object here: https://xlsxwriter.readthedocs.io/workbook.html

    but you should be able to create your new sheet with the above line of code.