You may already know how to save your Google Sheets data as an xlsx, tsv, csv & ods file by using the File > Download menu. But did you know that you can also generate a URL that will do this for you automatically? This way, we can make Google Sheets act as a simple database, so we can download the Google Sheets data in CSV format from a Python code.
Step 1: Make the Google Sheet downloadable ➥
- Open the Google Sheet you want to download as a CSV file.
- Click the Share button in the top right corner of the sheet.
- In the Share dialog, click the Advanced link.
- Under Who has access, select Anyone with the link.
- Copy the URL in the Link field.
Step 2: Create URL for downloading in CSV format. ➥
Anyone who has the URL from the previous step can access the Google Sheet using the Google Sheets app. The URL is similar to below.
https:// docs.google.com/spreadsheets/d/1234567890/edit?usp=sharing
To make a Google Sheet URL downloadable in CSV format, you can replace the edit?usp=sharing part of the URL with export?format=csv.
https:// docs.google.com/spreadsheets/d/1234567890/export?format=csv
Here 1234567890 is the ID of the Google Sheet file. The format=csv part of the URL tells Google Sheets to export the file as a CSV file, likewise for TSV format use format=csv.
Google Sheets can be used as a simple database, and you can download the data from your Python code.
Export Google Sheets to CSV Files with Python ➥
Here is a simple Python Script to Download Google Sheets and Save Them as CSV Files. This python code will download the Google Sheet with the ID 1234567890 to a CSV file in the tmp/ directory. The path to the CSV file will be printed to the console.
import os
import requests
import sys
def getGoogleSeet(spreadsheet_id, outDir, outFile):
url = f'https://docs.google.com/spreadsheets/d/{spreadsheet_id}/export?format=csv'
response = requests.get(url)
if response.status_code == 200:
filepath = os.path.join(outDir, outFile)
with open(filepath, 'wb') as f:
f.write(response.content)
print('CSV file saved to: {}'.format(filepath))
else:
print(f'Error downloading Google Sheet: {response.status_code}')
sys.exit(1)
##############################################
outDir = 'tmp/'
os.makedirs(outDir, exist_ok = True)
filepath = getGoogleSeet('1234567890', outDir, "devnodes.csv")
sys.exit(0); ## success