Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas: write dataframe to excel file *object* (not file)?

Tags:

python

pandas

I have a dataframe that I want to convert to excel file, and return it using HTTP. Dataframe's to_excel method accepts either a path, or an ExcelWriter, which, in turn, refers to a path.

Is there any way to convert the dataframe to a file object, without writing it to disk?

like image 898
blue_note Avatar asked Jul 10 '19 17:07

blue_note


People also ask

How do I export pandas to Excel without index?

Pandas to_excel() function has number of useful arguments to customize the excel file. For example, we can save the dataframe as excel file without index using “index=False” as additional argument. One of the common uses in excel file is naming the excel sheet.

How do you write to an Excel file in python without overwriting?

How to write to an existing Excel file without overwriting data using Python Pandas? To write to an existing Excel file without overwriting data using Python Pandas, we can use ExcelWriter . to create the ExcelWriter instance with the Excel file path. And then we call save to save the changes.


1 Answers

This can be done using the BytesIO Object in the standard library:

import pandas
from io import BytesIO

# Create Random Data for example
cols = ["col1", "col2"]
df = pandas.DataFrame.from_records([{k: 0.0 for k in cols} for _ in range(25)])

# Create an in memory binary file object, and write the dataframe to it.
in_memory_fp = BytesIO()
df.to_excel(in_memory_fp)

# Write the file out to disk to demonstrate that it worked.
in_memory_fp.seek(0,0)
with open("my_file.xlsx", 'wb') as f:
    f.write(in_memory_fp.read())

In the above example, I wrote the object out to a file so you can verify that it works. If you want to just return the raw binary data in memory all you need is:

in_memory_fp.seek(0,0)
binary_xl = in_memory_fp.read()
like image 166
Alex Avatar answered Nov 07 '22 11:11

Alex