0

I need to do a get to a URL with certain Headers and Parameters in my python code and then write to an excel file. I am trying the below code but getting the below error when I try to open the excel file. Also given below is a redacted version of a CURL I use to test this API endpoint with success that I cannot replicate in my python code

Python Code:

import requests
rheaders = {
            "Content-type": "application/json",
             "Accept": "application/json",
             "Authorization": "Token XXX",
}
url = "https://api.YYY"
r = requests.get(url, headers=rheaders)
with open("test.xlsx" , mode="wb") as output:
    output.write(r.content)

Error: Excel cannot open the file 'test.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.

The assosciated CURL that runs fine in osx terminal and writes the output file without errors

curl -H "Accept: application/json; indent=4" -H 'Content-Type: application/json' -H 'Authorization: Token XXX' https://api.YYY --output ~/Downloads/output.xlsx

I have tried replacing the content-type header with this:

Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

No luck. Any suggestions? The above is my attempt with python library requests. I have also tried using aiohttp

  • Does this answer your question? [Using Python, write an Excel file with columns copied from another Excel file](https://stackoverflow.com/questions/16560289/using-python-write-an-excel-file-with-columns-copied-from-another-excel-file) – Joshua Varghese Apr 07 '20 at 09:22

1 Answers1

0

The issue is that Excel cannot understand the format of the data that is being written into the file, because Python by itself does not support the Excel format. Try using a library such as xlrd to write to it. Alternatively, you could write to a .csv file instead, which wouldn't require any extra libraries and would still be readable by Excel

awarrier99
  • 3,628
  • 1
  • 12
  • 19