Creating a Table to Google Document by Retrieving Values from Google Spreadsheet for Golang

Gists

This is a sample script for creating a table to Google Document by retrieving values from Google Spreadsheet for Golang.

Before you use this script, please install go library of go-gdoctableapp.

$ go get -v -u github.com/tanaikech/go-gdoctableapp

Sample script:

This sample script uses Service Account.

In this sample script, the values are retrieved from Sheet1!A1:C5 of Spreadsheet, and new table is created to the Document using the values.

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"

	gdoctableapp "github.com/tanaikech/go-gdoctableapp"
	"golang.org/x/oauth2"
	"golang.org/x/oauth2/google"
	"golang.org/x/oauth2/jwt"
	docs "google.golang.org/api/docs/v1"
	sheets "google.golang.org/api/sheets/v4"
)

// ServiceAccount : Use Service account
func ServiceAccount(credentialFile string) *http.Client {
	b, err := ioutil.ReadFile(credentialFile)
	if err != nil {
		log.Fatal(err)
	}
	var c = struct {
		Email      string `json:"client_email"`
		PrivateKey string `json:"private_key"`
	}{}
	json.Unmarshal(b, &c)
	config := &jwt.Config{
		Email:      c.Email,
		PrivateKey: []byte(c.PrivateKey),
		Scopes: []string{
			docs.DocumentsScope,
			sheets.SpreadsheetsScope,
		},
		TokenURL: google.JWTTokenURL,
	}
	client := config.Client(oauth2.NoContext)
	return client
}

func main() {
	spreadsheetID := "###" // Please set here
	documentID := "###"    // Please set here

	client := ServiceAccount("credential.json") // Please set the json file of Service account.
	srv, err := sheets.New(client)
	if err != nil {
		log.Fatalf("%v", err)
	}

	// Retrieve values from Spreadsheet.
	sheetValues, err := srv.Spreadsheets.Values.Get(spreadsheetID, "Sheet1!A1:C5").Do()
	if err != nil {
		log.Fatalf("%v", err)
	}
	values := sheetValues.Values

	// Put the retrieved values to Document.
	g := gdoctableapp.New()
	obj := &gdoctableapp.CreateTableRequest{
		Rows:    int64(len(values)),
		Columns: int64(len(values[0])),
		Append:  true,
		Values:  values,
	}
	res, err := g.Docs(documentID).CreateTable(obj).Do(client)
	if err != nil {
		log.Fatalf("%v", err)
	}
	fmt.Println(res)
}

References:

 Share!