4

go กับ google sheets

 3 years ago
source link: https://dev.to/pallat/go-google-sheets-2iga
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

googleapis (2 Part Series)

การเขียน Go เพื่อไปอ่านหรือเขียนใน Google Sheets ต้องทำอะไรบ้าง

วันที่ทดลองใช้ go version 1.16.5

สิ่งที่ต้องเตรียม

  1. Google Account ซึ่งจะใช้ของส่วนตัวมาทดลองดูก็ได้
  2. Google Cloud ก็ใช้ account เดียวกับข้อ 1.
  3. ติดตั้ง Go ในเครื่องให้เรียบร้อย

เตรียม Google Sheet

  • สร้างไฟล์ใน Google Sheet ไว้ 1 file ตั้งชื่อให้เรียบร้อย
  • ตั้งชื่อ Sheet ไว้สักหน่อย เช่น Sheet1 เป็นต้น
  • จะเพิ่มข้อมูลไว้เล่นๆดูสักหน่อยก็แล้วแต่เลย
  • กด Share เอาแบบ public ไปเลย

สร้าง Service Account

  • ไปที่ Google Console
  • ไปที่เมนู APIs & Services
  • ถ้ายังไม่มี Project ก็สร้างเลย
  • กด Enable APIS AND SERVICES
  • ค้นหาด้วยคำว่า sheets จะเจอ Google Sheets API กดเข้าไปเลย
  • ไปสร้าง Service Account แล้ว Download json file

เขียนโค้ดสิครับ รออะไร

package main

import (
    "context"
    "fmt"
    "io/ioutil"
    "log"

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

func main() {
    ctx := context.Background()
    b, err := ioutil.ReadFile("./ไฟล์ที่donwloadมา.json")
    if err != nil {
        log.Fatalf("Unable to read client secret file: %v", err)
    }

    config, err := google.JWTConfigFromJSON(b, "https://www.googleapis.com/auth/spreadsheets")
    if err != nil {
        log.Fatalf("Unable to parse client secret file to config: %v", err)
    }
    client := config.Client(oauth2.NoContext)

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

    spreadsheetId := "idที่shareเอกสารมา"
    readRange := "A1:E1"
    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 {
            fmt.Printf("%s, %s\n", row[0], row[4])
        }
    }

    rb := &sheets.ValueRange{
        MajorDimension: "ROWS",
        Values: [][]interface{}{
            {"AAAA"},
        },
    }

    _, err = srv.Spreadsheets.Values.Append(spreadsheetId, "Sheet1!A2:A2", rb).ValueInputOption("USER_ENTERED").Do()
    if err != nil {
        log.Fatalf("Unable to append data to sheet: %v", err)
    }
}

Enter fullscreen modeExit fullscreen mode

ไม่ได้ capture รูปให้ดูนะครับ ขออภัย คิดว่ากดๆตาม ในช่วงเวลาเดียวกัน น่าจะไม่ยากมากครับ


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK