python xlsxwriter在一个Excel中导出数据框并以图形方式将图形绘制到不同的选项卡

问题描述

我正在尝试将一些数据框和可绘制的图形导出到一个Excel中的不同选项卡。每个选项卡应仅包含一个数据框或图形。我已经完成了数据框导出部分,但是我不知道如何使用类似的逻辑来导出绘图。

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()

然后我有另外两个数据帧制成的两个绘图图

# 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()

因此,总共应该有四个选项卡。 “上载”标签包含table,“其他用户标签包含misc_user,“用户标签包含user_evt_long,“主要用户”包含top_users_fig

如何使用与数据框导出类似的逻辑导出user_evt_longtop_users_fig

解决方法

请检查代码段。您可以使用openpyxl将图像和数据框插入单独的标签。每次您需要提及要创建的选项卡名称时。

这只是我创建的一个示例示例。您可以根据需要对其进行修改。但是它会根据需要创建4个标签。

您首先需要使用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):
         active3.cell(row=r_idx,value=value)
wb.save('new.xlsx')

您可以引用static-image-export以及 df.to_excel using openpyxl了解更多详情

,

这是一个将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,30,15,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,{'image_data': image_data})

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

输出

enter image description here

请注意,也可以直接在Xlsxwriter中绘制来自Pandas数据框的图表。请参阅XlsxWriter文档的Adding Charts to Dataframe output部分。