python-2.7google-sheets-api

How to import a CSV file using Google Sheets API V4


Background

I'm developing a Python 2.7 script that analyzes data from an SQL table and at the end, generates a CSV file.

Once the file is generated, I'm logging into my google sheet account and use the import option to import my CSV file into the google spreadsheet

The manual labor is kinda stupid and I wish to add this ability to my script.

Google Sheets API V4

So, I followed this guide, Python Quickstart and was able to complete all the steps.

Then I followed Google Sheets API reference and looked into Method: spreadsheets.create. If I understand correctly, it does not provides the options to import from a file.

It seems like there is no API for the import functionality.

Question

How to import a CSV file using Google Sheets API V4? Is their an example/reference that I'm missing?


Solution

  • Another alternative to Sam Berlin's answer. If you're using Python, you can use the Drive API via gspread to import a CSV file. Here's an example:

    import gspread
    
    # Check how to get `credentials`:
    # https://github.com/burnash/gspread
    
    gc = gspread.authorize(credentials)
    
    # Read CSV file contents
    content = open('file_to_import.csv', 'r').read()
    
    gc.import_csv('<SPREADSHEET_ID>', content)
    

    Related question: Upload CSV to Google Sheets using gspread