Python:将图像和数据框写入相同的excel文件 [英] Python: Writing Images and dataframes to the same excel file

查看:57
本文介绍了Python:将图像和数据框写入相同的excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个excel仪表板,我想生成一个excel工作簿,该工作簿的一半有一些数据框,另一半有.png文件.我很难一口气将它们写入同一文件.这是我目前所拥有的.看来,当我运行我的for循环时,它不会让我添加其他工作表.关于如何将图像文件添加到此工作簿的任何建议?我找不到任何关于为什么我无法添加更多工作表的信息,谢谢!

I'm creating an excel dashboard and I want to generate an excel workbook that has some dataframes on half of the sheets, and .png files for the other half. I'm having difficulty writing them to the same file in one go. Here's what I currently have. It seems that when I run my for loop, it won't let me add additional worksheets. Any advice on how I might get my image files added to this workbook? I can't find anything about why I can't add any more worksheets Thanks!

dfs = dict()
dfs['AvgVisitsData'] = avgvisits
dfs['F2FCountsData'] = f2fcounts

writer = pd.ExcelWriter("MyData.xlsx", engine='xlsxwriter')
for name, df in dfs.items():
    df.to_excel(writer, sheet_name=name, index = False)

然后我想将带有一些图像的几张纸添加到同一张excel工作簿中.这样的东西,但是我没有创建一个全新的工作簿.

Then I want to add a couple sheets with some images to the same excel workbook. Something like this, but where I'm not creating a whole new workbook.

workbook = xlsxwriter.Workbook('MyData.xlsx')
worksheet = workbook.add_worksheet('image1')
worksheet.insert_image('A1', 'MemberCollateral.png')

有人对此有任何建议吗?

Anyone have any tips to work around this?

推荐答案

以下是如何获取基础XlsxWriter工作簿和工作表对象的句柄并插入图像的示例:

Here is an example of how to get a handle to the underlying XlsxWriter workbook and worksheet objects and insert an image:

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_image.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']

# Insert an image.
worksheet.insert_image('D3', 'logo.png')

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

输出:

另请参阅XlsxWriter文档中的使用Python熊猫和XlsxWriter

See also Working with Python Pandas and XlsxWriter in the XlsxWriter docs for more examples

这篇关于Python:将图像和数据框写入相同的excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆