Home > Mobile >  How to write a Dataframe and images to separate worksheets of an excel file
How to write a Dataframe and images to separate worksheets of an excel file

Time:10-21

I have found a similar and well answered question, Python: Writing Images and dataframes to the same excel file, but the answer writes the image into the same sheet as the Dataframe. I have 5 images I want to write to separate worksheet to that of the Dataframe. As this answer is well written I shall use it here if that is ok and ask how to write any 2 images to a separate worksheet in the created workbook?

Code

import pandas as pd


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

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_image2.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')

# Get the xlsxwriter workbook and worksheet objects.
workbook  = writer.book
worksheet = writer.sheets['Sheet2']

# Insert an image.
worksheet.insert_image('D3', 'TRAJ_FIG.PNG')

# Close the Pandas Excel writer and output the Excel file.
writer.save()

Desired result

An excel workbook with two sheets, the df written to one and 2 images written to the other worksheet.

CodePudding user response:

Instead of using writer, add a new sheet using workbook.add_worksheet():

with pd.ExcelWriter('pandas_image2.xlsx', engine='xlsxwriter') as writer:
    df.to_excel(writer, sheet_name='Sheet1')

    workbook  = writer.book
    worksheet = workbook.add_worksheet('Sheet2')
    worksheet.insert_image('D3', 'TRAJ_FIG.PNG')
  • Related