Skip to content

Instantly share code, notes, and snippets.

@imantung
Last active April 17, 2023 00:48
Show Gist options
  • Save imantung/2b0cf4d8ba5f8b49289927418c06126b to your computer and use it in GitHub Desktop.
Save imantung/2b0cf4d8ba5f8b49289927418c06126b to your computer and use it in GitHub Desktop.
Golang GSheet
package main
import (
"context"
"fmt"
"log"
"google.golang.org/api/option"
"google.golang.org/api/sheets/v4"
)
// Example to read/write gsheet using https://github.com/googleapis/google-api-go-client
var (
// 1.Select project at https://console.cloud.google.com or create new at https://console.cloud.google.com/projectcreate
// 2. Select service account account management at https://console.cloud.google.com/iam-admin/serviceaccounts or create new at https://console.cloud.google.com/iam-admin/serviceaccounts/create
// 3. In service account detail, go to tab "KEYS" and click "ADD KEY", choose JSON to create credential json
CredJson = `{
"type": "service_account",
"project_id": "",
"private_key_id": "",
"private_key": "",
"client_email": "",
"client_id": "",
"auth_uri": "",
"token_uri": "",
"auth_provider_x509_cert_url": "",
"client_x509_cert_url": ""
}`
// SpreadSheet ID is same with path in GSheet Link
// Give editor access for "client_email" on the GSheet using Share menu
// Original Link: https://docs.google.com/spreadsheets/d/[SPREADSHEET_ID]
spreadsheetId = "[SPREADSHEET_ID]"
)
func main() {
ctx := context.Background()
svc, err := sheets.NewService(ctx,
option.WithCredentialsJSON([]byte(CredJson)), // or option.WithCredentialsFile() to read credential from file
)
fatalIfError(err, "Unable to retrieve Sheets client")
// read example
readRange := "Sheet1!A3:D12"
resp, err := svc.Spreadsheets.Values.Get(spreadsheetId, readRange).Do()
fatalIfError(err, "Unable to retrieve data from sheet")
for _, row := range resp.Values {
fmt.Printf("%s, %s\n", row[0], row[2]) // Print columns A and C, which correspond to indices 0 and 2.
}
// write example
writeRange := "Sheet1!A1"
var vr sheets.ValueRange
vr.Values = append(vr.Values, []interface{}{"Hello", "World"})
_, err = svc.Spreadsheets.Values.Update(spreadsheetId, writeRange, &vr).ValueInputOption("RAW").Do()
fatalIfError(err, "Unable to retrieve data from sheet")
}
func fatalIfError(err error, info string) {
if err != nil {
log.Fatalf("%s: %v", info, err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment