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?
I like Burnash's gspread library, but the
import_csv
function in his answer is limited. It always starts the paste atA1
of the first worksheet (tab) and deletes all other tabs.I needed to paste starting at a particular tab and cell, so I took Sam Berlin's suggestion to use a PasteDataRequest. Here's my function:
Note that I used a raw pasteData request rather than the higher-level
update_cells
method to take advantage of Google's automatic (correct) handling of input data that contains quoted strings, which may contain non-delimeter commas.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:
Related question: Upload CSV to Google Sheets using gspread
You have two options for importing g CSV file. You can use the Drive API to create a spreadsheet from a CSV, or you can use the Sheets API to create an empty spreadsheet and then use spreadsheets.batchUpdate with a PasteDataRequest to add CSV data.
An alternative to Sam Berlin's answer, you can turn your CSV into a list of lists and set that to your POST payload.
Such a function looks something like this:
That master array gets thrown into the following:
It works just fine for me.