Last active
December 6, 2017 06:10
-
-
Save grant/516499dee6b6d69e7a415b277026ba63 to your computer and use it in GitHub Desktop.
Sheets Quickstart – Go alternative (developers.google.com/sheets/api/quickstart/go)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
) | |
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit | |
var SpreadsheetId = "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms" | |
func getSpreadsheetValues() { | |
// Prints the names and majors of students in a sample spreadsheet: | |
readRange := "Class Data!A2:E" | |
resp, err := getService().Spreadsheets.Values.Get(SpreadsheetId, readRange).Do() | |
if err != nil { | |
log.Fatalf("Unable to retrieve data from sheet. %v", err) | |
} | |
fmt.Println("Name, Major:") | |
for _, row := range resp.Values { | |
// Print columns A and E, which correspond to indices 0 and 4. | |
fmt.Printf("%s, %s\n", row[0], row[4]) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"google.golang.org/api/sheets/v4" | |
"io/ioutil" | |
"golang.org/x/oauth2/google" | |
"golang.org/x/oauth2" | |
"context" | |
) | |
// getTokenFromWeb uses Config to request a Token. | |
// It returns the retrieved Token. | |
func getTokenFromWeb(config *oauth2.Config) *oauth2.Token { | |
authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline) | |
fmt.Printf("Go to the following link in your browser then type the "+ | |
"authorization code: \n%v\n", authURL) | |
var code string | |
if _, err := fmt.Scan(&code); err != nil { | |
log.Fatalf("Unable to read authorization code %v", err) | |
} | |
tok, err := config.Exchange(context.Background(), code) | |
if err != nil { | |
log.Fatalf("Unable to retrieve token from web %v", err) | |
} | |
return tok | |
} | |
func getService() (*sheets.Service, error){ | |
clientSecret, err := ioutil.ReadFile(ClientSecretFilename) | |
if err != nil { | |
log.Fatalf("Unable to read client secret file: %v", err) | |
} | |
config, err := google.ConfigFromJSON(clientSecret, sheets.SpreadsheetsReadonlyScope) | |
if err != nil { | |
log.Fatalf("Unable to parse client secret file to config: %v", err) | |
} | |
client := config.Client(context.Background(), getTokenFromWeb(config)) | |
return sheets.New(client) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment