DEV Community

Updating Google Sheets using Golang.

Leon Nunes on November 08, 2020

At work I'm mostly working with Google Sheets there is a lot of manual work that goes into this, this script basically takes data from a MySQL DB(L...
Collapse
 
akhilraj profile image
Akhil Raj

In case you are getting this error :

Error 403: The caller does not have permission, forbidden
exit status 1

Make sure that the the link of the spreadsheet that you are giving, there should be permission to edit on that link.

Collapse
 
silvioprog profile image
silvioprog

Worked for me by following this tutorial: prudentdevs.club/gsheets-go

Please take a look at the picture below:

Image description

My code was:

package main

import (
    "context"
    "fmt"
    "log"
    "os"

    "golang.org/x/oauth2/google"
    "google.golang.org/api/option"
    "google.golang.org/api/sheets/v4"
)

func main() {
    data, err := os.ReadFile("secret.json")
    if err != nil {
        log.Fatalf("Unable to read client secret file: %v", err)
    }

    conf, err := google.JWTConfigFromJSON(data, sheets.SpreadsheetsScope)
    if err != nil {
        log.Fatalf("Unable to parse JWT to config: %v", err)
    }

    ctx := context.TODO()

    client := conf.Client(ctx)
    srv, err := sheets.NewService(ctx, option.WithHTTPClient(client))
    if err != nil {
        log.Fatalf("Unable to retrieve Sheets client: %v", err)
    }

    // Prints the names and majors of students in a sample spreadsheet:
    spreadsheetId := "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms"
    readRange := "Class Data!A2:E"
    resp, err := srv.Spreadsheets.Values.Get(spreadsheetId, readRange).Do()
    if err != nil {
        log.Fatalf("Unable to retrieve data from sheet: %v", err)
    }

    if len(resp.Values) == 0 {
        fmt.Println("No data found.")
    } else {
        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])
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
erdauletbatalov profile image
Yerdaulet Batalov

You just saved my day maaan! Thank you!

Collapse
 
mediocredevops profile image
Leon Nunes

Heya, glad it helped you :) makes me happy