user1592380
user1592380

Reputation: 36205

How can you upload csv file to create a google sheets project with python

I'm interested in uploading a csv to google sheets/drive to create a shareable spreadsheet. Reading through https://developers.google.com/sheets/api/samples/ I'm not sure how. Any advice would be appreciated

Upvotes: 0

Views: 1675

Answers (1)

Tanaike
Tanaike

Reputation: 201378

If you already have access token, please skip following 3 steps.

  1. Retrieve Client ID, Client Secret at Google Developers Console. Scope is "https://www.googleapis.com/auth/drive".

  2. Retrieve code using Client ID.

  3. Retrieve access token using Client ID, Client Secret, code and redirect URI.

Reference is https://developers.google.com/identity/protocols/OAuth2#scenarios.

Python script:

import json
import requests

accessToken = "#####"
csvfile = "#####"

headers = {"Authorization": "Bearer " + accessToken}
metadata = {
    "name": csvfile,
    "mimeType": "application/vnd.google-apps.spreadsheet"
}
files = {
    "data": ("metadata", json.dumps(metadata), "application/json"),
    "file": (csvfile, open(csvfile, "rt"), "text/csv")
}
requests.post(
    "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
    headers=headers,
    files=files
)

This is a very simple sample script to upload a CSV file and convert to spreadsheet with CSV file name. If you want to change file name of spreadsheet, please change "name". If I misunderstand what you want, I apologize.

Upvotes: 2

Related Questions