使用Pandas Excelwriter写入StringIO对象? [英] Write to StringIO object using Pandas Excelwriter?

查看:9054
本文介绍了使用Pandas Excelwriter写入StringIO对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以传递一个StringIO对象到pd.to_csv()很好:

I can pass a StringIO object to pd.to_csv() just fine:

io = StringIO.StringIO()
pd.DataFrame().to_csv(io)

但是当使用excel作者时,我有更多的麻烦

But when using the excel writer, I am having a lot more trouble.

io = StringIO.StringIO()
writer = pd.ExcelWriter(io)
pd.DataFrame().to_excel(writer,"sheet name")
writer.save()   

返回一个

AttributeError: StringIO instance has no attribute 'rfind'

我正在尝试创建一个 ExcelWriter 对象而不调用 pd.ExcelWriter() 但是有一些麻烦。这是我迄今为止所尝试的:

I'm trying to create an ExcelWriter object without calling pd.ExcelWriter() but am having some trouble. This is what I've tried so far:

from xlsxwriter.workbook import Workbook
writer = Workbook(io)
pd.DataFrame().to_excel(writer,"sheet name")
writer.save()

但是现在我得到一个 AttributeError:'Workbook'对象没有属性'write_cells'

如何将大熊猫数据框以excel格式保存到 StringIO 对象?

How can I save a pandas dataframe in excel format to a StringIO object?

推荐答案

Pandas期望ExcelWriter构造函数的文件名路径,尽管每个作者引擎都支持 StringIO 。也许这应该是在熊猫的bug /功能请求中提出的。

Pandas expects a filename path to the ExcelWriter constructors although each of the writer engines support StringIO. Perhaps that should be raised as a bug/feature request in Pandas.

同时,这里是一个使用Pandas xlsxwriter 引擎:

In the meantime here is a workaround example using the Pandas xlsxwriter engine:

import pandas as pd
import StringIO

io = StringIO.StringIO()

# Use a temp filename to keep pandas happy.
writer = pd.ExcelWriter('temp.xlsx', engine='xlsxwriter')

# Set the filename/file handle in the xlsxwriter.workbook object.
writer.book.filename = io

# Write the data frame to the StringIO object.
pd.DataFrame().to_excel(writer, sheet_name='Sheet1')
writer.save()
xlsx_data = io.getvalue()

更新:从Pandas 0.17起,现在可以直接进行更改:

Update: As of Pandas 0.17 it is now possible to do this more directly:

# Note, Python 2 example. For Python 3 use: output = io.BytesIO().
output = StringIO.StringIO()

# Use the StringIO object as the filehandle.
writer = pd.ExcelWriter(output, engine='xlsxwriter')

另请参见< a href =http://xlsxwriter.readthedocs.io/working_with_pandas.html#saving-the-dataframe-output-to-string =noreferrer>将Dataframe输出保存到字符串 XlsxWriter文档。

See also Saving the Dataframe output to a string in the XlsxWriter docs.

这篇关于使用Pandas Excelwriter写入StringIO对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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