Search code examples
pythonpython-3.xpandaspandas.excelwriter

Accessing Excel files directly from RAM using Excel Writer


In the documentation for pd.ExcelWriter we see the following code snippet:

You can store Excel file in RAM:

import io
df = pd.DataFrame([["ABC", "XYZ"]], columns=["Foo", "Bar"])
buffer = io.BytesIO()
with pd.ExcelWriter(buffer) as writer:
     df.to_excel(writer)

My question is that how can we access the excel back. I wanted to have the b64 coded version of the same excel without saving the file in the system that is why I am thinking of saving it in my RAM. Can someone please help on this?

Thanks for your time

Solution: Was able to access the file using buffer.getvalue().


Solution

  • In the snippet you provided, the Excel file has been written to the buffer the same way as if it would have been stored on disk.

    Therefore you can read it back in a similar way as if you were reading from file:

    pd.read_excel(buffer.getvalue())
    

    More on how BytesIO behave: