pythonpandaspython-requestsxlrd

Python: How to read excel file from Requests response?


I am downloading an excel file as a stream using the requests library.

r = requests.get(my_url, stream=True)

I want to read the data in this excel file, for that I can am trying to use pandas. But I am not sure how to read the file from the response I get. What can I do?


Solution

  • You can use a url in pandas directly to read the excel file without using requests.

    import pandas as pd
    
    df = pd.read_excel(my_url)
    

    If it is necessary to retreive the data via requests, then this answer from here (How to download a Excel file from behind a paywall into a pandas dataframe?) may suffice:

    Simply wrap the file contents in a BytesIO:

    import pandas as pd
    import io
    
    with io.BytesIO(r.content) as fh:
        df = pd.io.excel.read_excel(fh, sheet_name=0) #sheetname becomes sheet_name