小编典典

使用Pandas Excelwriter写到StringIO对象?

python

我可以将StringIO对象传递给pd.to_csv()很好:

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

但是当使用excel编写器时,我遇到了很多麻烦。

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()但是遇到了一些麻烦。到目前为止,这是我尝试过的:

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

但是现在我得到了 AttributeError: 'Workbook' object has no attribute 'write_cells'

如何将Excel格式的熊猫数据框保存到StringIO对象?


阅读 220

收藏
2020-12-20

共1个答案

小编典典

尽管每个编写器引擎都支持,但Pandas期望ExcelWriter构造函数的文件名路径StringIO。也许应该将其作为熊猫中的错误/功能请求提出。

同时,这是使用Pandasxlsxwriter引擎的解决方法示例:

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开始,现在可以更直接地执行此操作:

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

另请参阅XlsxWriter文档中的将数据框输出保存到字符串

2020-12-20