2

Want to download to local directory. This code works for csv but not xlsx. It writes a file but cannot be opened as Excel.

Any help will be appreciated.

url = 'https://some_url'
resp = requests.get(url)
open('some_filename.xlsx', 'wb').write(resp.content)
Patrick Ng
  • 76
  • 6
  • did u check https://stackoverflow.com/a/42703510/6660638? Changing the extension does not mean changing the content inside the file – Epsi95 Aug 24 '21 at 07:16
  • I am slightly unclear. Is the file on the server already a .xlsx file (which you can download manually and open from Excel)? – DS_London Aug 24 '21 at 07:18
  • Yes, source file is already xlsx on server. – Patrick Ng Aug 24 '21 at 07:22
  • Fwiw, I download files using `urllib`, as `import urllib.request as ur`, then simply `ur.urlretrieve(url, localFile)` to download the file. Perhaps try that and see if the downloaded file is OK. – DS_London Aug 24 '21 at 10:36

2 Answers2

1

You could create a dataframe from the resp data and then use pd.to_excel() function to obtain the xlsx file. This is a tested solution, and it worked for me.

import requests
import pandas as pd
import io

url='https://www.google.com' #as an example
urlData = requests.get(url).content  #Get the content from the url
dataframe = pd.read_csv(io.StringIO(urlData.decode('latin-1'))) 
filename="data.xlsx"
dataframe.to_excel(filename)
MariCruzR
  • 147
  • 8
  • @Patrick_Ng I've updated my comment, because I got to test the proposed solution and it worked. Please, confirm if this has worked for you also. – MariCruzR Aug 24 '21 at 08:14
0

In pandas you could just do:

import pandas as pd
url = 'https://some_url'
df = pd.read_csv(url)
U13-Forward
  • 69,221
  • 14
  • 89
  • 114