简体   繁体   中英

python xlsxwriter export dataframe and plotly graphs to different tabs in one excel

I'm trying to export some dataframes and plotly graphs to different tabs in one excel. Each tab shall contain only one dataframe or graph. I had the dataframe export part done but I don't know how to export the plotly graphs using similar logic.

Xlsxwriter: exporting two dataframes: table and misc_user

writer = pd.ExcelWriter(path_output + '\Report_{}.xlsx'.format(*arg), engine='xlsxwriter')

table.to_excel(writer, sheet_name='Uploads')
misc_user.to_excel(writer, sheet_name='Misc Users')

writer.save()

I then have two plotly graphs made from two other dataframes

# plotly 
user_evt_long = px.line(user_evt_long, x='Month', y='Times', color='ELEVATE?')

# Show plot 
user_evt_long.show()
top_users_fig = px.bar(top_users, x='account_name', y='users_count', title = 'Top Ten Uploads')

top_users_fig.show()

So there shall be four tabs in total. 'Uploads' tab contains table , 'Misc users' tab contains misc_user , 'Users' tab contains user_evt_long , and 'Top Users' contains top_users_fig .

How can I export user_evt_long and top_users_fig using similar logic as the dataframe export?

Here's an example of adding a Plotly image to the same worksheet as the Pandas dataframe and also to a new worksheet.

import plotly.express as px
import pandas as pd
from io import BytesIO


# 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_plotly.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['Sheet1']

# Make a plotly chart.
fig = px.bar(df)

# Convert it to a BytesIO stream.
image_data = BytesIO(fig.to_image(format="png"))

# Write the image to the same sheet as the data.
worksheet.insert_image(2, 3, 'plotly.png', {'image_data': image_data})

# Create a new worksheet and add the image to it.
worksheet = workbook.add_worksheet()
worksheet.insert_image(2, 3, 'plotly.png', {'image_data': image_data})

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

Output :

在此处输入图片说明

Note, it is also possible to plot charts from Pandas dataframes directly in Xlsxwriter. See the Adding Charts to Dataframe output section of the XlsxWriter docs.

Please check the snippet. You can use openpyxl to insert image and dataframe to separate tabs. Each time you would need to mention tab name you are creating.

This is just a sample example which i created . You can modify it as per your requirement. But it creates 4 tags as you require.

You would need to first save your image using fig.write_image then only you would be able to insert it.

from openpyxl import Workbook
from openpyxl.drawing.image import Image
from openpyxl.utils.dataframe import dataframe_to_rows
import plotly.graph_objects as go
import plotly
import pandas as pd

data = [['Ravi',21,67],['Kiran',24,61],['Anita',18,46],['Smita',20,78],['Sunil',17,90]]
df = pd.DataFrame(data,columns = ['name','age','marks'],dtype = float)
trace = go.Bar(x = df.name, y = df.marks)
fig = go.Figure(data = [trace])
fig.write_image("Plotly1.png")

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

sheet2 = wb.create_sheet('image2',0)
active1 = wb['image2']
active1.add_image(Image('Plotly1.png'),'A1')

sheet3 = wb.create_sheet('marks',0)
active2 = wb['marks']
rows = dataframe_to_rows(df)

for r_idx, row in enumerate(rows, 1):
    for c_idx, value in enumerate(row, 1):
         active2.cell(row=r_idx, column=c_idx, value=value)

sheet4 = wb.create_sheet('marks1',0)
active3 = wb['marks1']
rows1 = dataframe_to_rows(df)
for r_idx, row in enumerate(rows1, 1):
    for c_idx, value in enumerate(row, 1):
         active3.cell(row=r_idx, column=c_idx, value=value)
wb.save('new.xlsx')

You can refer static-image-export as well as df.to_excel using openpyxl for more details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM