Pandas XLSWriter - return instead of write

后端 未结 1 1874
灰色年华
灰色年华 2021-01-14 21:50

I want to return an Excel file from my Flask (Python) server. This code:

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


        
相关标签:
1条回答
  • 2021-01-14 22:37

    You can write the excel data to memory using a StringIO or BytesIO object.

    This code is copied from the pandas documentation 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()
    
    0 讨论(0)
提交回复
热议问题