how to save a plotly graph to excel sheet as an image using python?

Viewed 3273

I created a plotly fig and now, I'm trying to write this fig to excel file as an image.

How can I do this using Python?

data = []
data.append(
    go.Bar(
    x=df['id'],
    y=df['normalize energy'], 
    hoverlabel = dict(namelength = -1)
    )
)    
layout = dict(
        title="energy" ,
        xaxis=dict(
            title='id'
        ),
        yaxis=dict(
            title='energy [W]',
            titlefont=dict(
                color='rgb(148, 103, 189)'
            ),
            tickfont=dict(
                color='rgb(148, 103, 189)'
            ),
            overlaying='y',
            side='right',
            fixedrange=False
        ),   
        height= 600
    )
fig = go.FigureWidget(data)
fig.layout = layout
fig

writer = pd.ExcelWriter(path)
df.to_excel(writer,'Sheet1')
writer.save()

I want to add the fig to the excel sheet as well.

1 Answers

You could use a combination of orca (for static image generation) and openpyxl (for writing images into an excel file).

In order to install orca, see the official doc.

Then, append this lines to your code:

fig.write_image("fig.png")

from openpyxl import Workbook
from openpyxl.drawing.image import Image

wb = Workbook()
sheet1 = wb.create_sheet('sheet1',0)
active = wb['sheet1']
active.add_image(Image('fig.png'),'A1')

wb.save('myfile.xlsx')
Related