【问题标题】:Pandas XLSWriter - return instead of writePandas XLSXWriter - 返回而不是写入
【发布时间】:2018-10-20 20:47:48
【问题描述】:

我想从我的 Flask (Python) 服务器返回一个 Excel 文件。这段代码:

writer = pd.ExcelWriter('filename.xlsx')
dataframe.to_excel(writer, index=False)
writer.save()

将 Excel 文件写入文件系统。我怎样才能return 文件而不是写它?

【问题讨论】:

    标签: python excel pandas


    【解决方案1】:

    您可以使用StringIOBytesIO 对象将excel 数据写入内存。

    此代码复制自 pandas 文档here

    # Safe import for either Python 2.x or 3.x
    try:
        from io import BytesIO
    except ImportError:
        from cStringIO import StringIO as BytesIO
    
    bio = BytesIO()
    
    # By setting the 'engine' in the ExcelWriter constructor.
    writer = ExcelWriter(bio, engine='xlsxwriter')
    df.to_excel(writer, sheet_name='Sheet1')
    
    # Save the workbook
    writer.save()
    
    # Seek to the beginning and read to copy the workbook to a variable in memory
    bio.seek(0)
    workbook = bio.read()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-04
      • 2017-03-30
      • 2018-11-18
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 2017-10-06
      • 2020-06-22
      相关资源
      最近更新 更多