pandas:如何将数据框写入Excel文件*对象*(而不是文件)?

7

我有一个数据框,想将其转换为Excel文件,并使用HTTP返回。数据框的to_excel方法接受路径或ExcelWriter,后者指的是路径。

是否有办法将数据框转换为文件对象,而不将其写入磁盘?


尝试使用 df.to_string 和 Python 的 io.StringIO - Andy L.
他,看一下这个链接 - wordinone
问题是,我想先将它转换为Excel格式,而不仅仅是将数据框转换为字节。 - blue_note
1个回答

10
使用标准库中的 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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接