尽管每个编写器引擎都支持,但Pandas期望ExcelWriter构造函数的文件名路径
StringIO。也许应该将其作为熊猫中的错误/功能请求提出。
同时,这是使用Pandas
xlsxwriter引擎的解决方法示例:
import pandas as pdimport StringIOio = 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文档中的将数据框输出保存到字符串。



