我有一个数据框,想将其转换为Excel文件,并使用HTTP返回。数据框的to_excel
方法接受路径或ExcelWriter
,后者指的是路径。
是否有办法将数据框转换为文件对象,而不将其写入磁盘?
BytesIO
对象可以完成此操作。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_memory_fp.seek(0,0)
binary_xl = in_memory_fp.read()
df.to_string
和 Python 的io.StringIO
。 - Andy L.