使用Pandas Excelwriter写入StringIO对象?
作者:互联网
我可以将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’对象没有属性’write_cells’
如何将excel格式的pandas数据帧保存到StringIO对象?
解决方法:
Pandas期望ExcelWriter构造函数的文件名路径,尽管每个编写器引擎都支持StringIO.也许这应该在Pandas中作为bug /功能请求引发.
与此同时,这是使用Pandas xlsxwriter引擎的变通方法示例:
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文档中的Saving the Dataframe output to a string.
标签:python,pandas,excel,xlsxwriter,stringio 来源: https://codeday.me/bug/20190925/1815969.html