- Install Go
- Google sheets package.
google.golang.org/api/sheets/v4 - Google cloud console
- Login to Google cloud console
- Navigate to APIs & Services
- Add Google Sheets API
- Goto Credentials, Add New
- Create service account, add Key
- Download the JSON file.
- Give service account Owner Role.
- Create project directory.
mkdir google-sheets-go - Change into the directory
cd google-sheets-go - Init the Go application
go mod init github.com/username/google-sheets-go - Install Go Google Sheets package.
go get google.golang.org/api/sheets/v4 - Add a main.go file.
touch main.go - Open the main.go file with your favorite IDE, I'm using vscode.
code . -r
- Load the credential (config.json) in to our code;
package main import ( "google.golang.org/api/option" "google.golang.org/api/sheets/v4" ) func main() { // Set up Google Sheets API client options := []option.ClientOption{ option.WithCredentialsFile("./config/config.json"), option.WithScopes(sheet.SpreadsheetsScope), } }
- Make a Google Sheets Service;
ctx := context.Background() // Create a new Sheets service srv, err := sheets.NewService(ctx, options...) if err != nil { log.Fatalf("Unable to create Sheets service: %v", err) }
- Create a new Spreadsheet;
sheet, err := srv.Spreadsheets.Create(&sheets.Spreadsheet{ Properties: &sheets.SpreadsheetProperties{ Title: "Financial Data", }, }).Do() if err != nil { log.Fatalf("Unable to create spreadsheet: %v", err) } log.Printf("Created spreadsheet with ID: %s", sheet.SpreadsheetId)
- Copy the service account email and share the Spreadsheet with the service account email using Google Sheet UI.
- Copy the Spreadsheet ID from the sheets URL.
- Define the readRange. e.g "Sheet1!A1:D1" ... Read Google sheets API docs
- Update or Append data into the sheet.
// Access a specific spreadsheet spreadsheetId := "spreadsheet-ID" readRange := "Sheet1!A1:D1" // represents first row // Append data to the spreadsheet _, err = srv.Spreadsheets.Values.Append(spreadsheetId, readRange, &sheets.ValueRange{ Values: [][]interface{}{ {"A", "B", "C", "D"}, }, }).ValueInputOption("RAW").Do() if err != nil { log.Fatalf("Unable to append data to sheet: %v", err) }
This is a basic and simple example showcasing how to manage Google sheets spreadsheets using Go, you can do a lot more with the google sheets API. Read the full documentation at https://developers.google.com/workspace/sheets/api/guides.