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

2024/9/30 22:59:25

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?

Answer

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()
https://en.xdnf.cn/q/70931.html

Related Q&A

win32: moving mouse with SetCursorPos vs. mouse_event

Is there any difference between moving the mouse in windows using the following two techniques?win32api.SetCursorPos((x,y))vs:nx = x*65535/win32api.GetSystemMetrics(0) ny = y*65535/win32api.GetSystemM…

Pandas: Unstacking One Column of a DataFrame

I want to unstack one column in my Pandas DataFrame. The DataFrame is indexed by the Date and I want to unstack the Country column so each Country is its own column. The current pandas DF looks like t…

python-polars split string column into many columns by delimiter

In pandas, the following code will split the string from col1 into many columns. is there a way to do this in polars? d = {col1: ["a/b/c/d", "a/b/c/d"]} df= pd.DataFrame(data=d) df…

pylint giving not-callable error for object property that is callable

Not sure if I am doing something wrong or if this is a problem with pylint. In the code below I get a linting error that self.type is not callable E1102.Although I could just ignore it and keep workin…

ModuleNotFoundError: No module named api

I created a Django project inside of api folder called bucks:api |____ categories/|____ __init__.py|____ ...|____ models.py|____ tests.py|____ views.py |____ .../ |____ bucks/ |____ users/|____ __init_…

Reading csv header white space and case insensitive

Is there a possibility to read the header of a CSV file white space and case insensitive? As for now I use csv.dictreader like this:import csv csvDict = csv.DictReader(open(csv-file.csv, rU))# determi…

How to remove the seconds of Pandas dataframe index?

Given a dataframe with time series that looks like this:Close 2015-02-20 14:00:00 1200.1 2015-02-20 14:10:00 1199.8 2015-02-21 14:00:00 1199.3 2015-02-21 14:10:00 1199.0 2015-02-22 14:00:00 1198.4…

Slow loading SQL Server table into pandas DataFrame

Pandas gets ridiculously slow when loading more than 10 million records from a SQL Server DB using pyodbc and mainly the function pandas.read_sql(query,pyodbc_conn). The following code takes up to 40-4…

compress a string in python 3?

I dont understand in 2.X it worked :import zlib zlib.compress(Hello, world)now i have a :zlib.compress("Hello world!") TypeError: must be bytes or buffer, not strHow can i compress my string …

How to set color of text using xlwt

I havent been able to find documentation on how to set the color of text. How would the following be done in xlwt?style = xlwt.XFStyle()# bold font = xlwt.Font() font.bold = True style.font = font# ba…