简体   繁体   English

python xlsxwriter 将数据框和绘图导出到一个 Excel 中的不同选项卡

[英]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.我正在尝试将一些数据框和绘图导出到一个 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 Xlsxwriter:导出两个数据帧:table 和 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 . 'Uploads' 选项卡包含table ,'Misc users' 选项卡包含misc_user ,'Users' 选项卡包含user_evt_long ,'Top Users' 包含top_users_fig

How can I export user_evt_long and top_users_fig using similar logic as the dataframe export?如何使用与数据帧导出类似的逻辑导出user_evt_longtop_users_fig

Here's an example of adding a Plotly image to the same worksheet as the Pandas dataframe and also to a new worksheet.这是将 Plotly 图像添加到与 Pandas 数据框相同的工作表以及新工作表的示例。

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.请注意,也可以直接在 Xlsxwriter 中从 Pandas 数据帧绘制图表。 See the Adding Charts to Dataframe output section of the XlsxWriter docs.请参阅 XlsxWriter 文档的将图表添加到数据帧输出部分。

Please check the snippet.请检查代码段。 You can use openpyxl to insert image and dataframe to separate tabs.您可以使用openpyxl将图像和数据openpyxl插入到单独的选项卡中。 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.但它会根据您的需要创建 4 个标签。

You would need to first save your image using fig.write_image then only you would be able to insert it.您需要先使用fig.write_image保存图像,然后才能插入它。

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您可以使用 openpyxl参考static-image-export以及df.to_excel 以获取更多详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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