0

我正在尝试在此处遵循 Google Sheets API 快速入门:

https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdate

(向下滚动到“示例”,然后单击“开始”)

这就是我尝试更新电子表格的方式:

package main

// BEFORE RUNNING:
// ---------------
// 1. If not already done, enable the Google Sheets API
//    and check the quota for your project at
//    https://console.developers.google.com/apis/api/sheets
// 2. Install and update the Go dependencies by running `go get -u` in     the
//    project directory.

import (
        "errors"
        "fmt"
        "log"
        "net/http"

        "golang.org/x/net/context"
        "google.golang.org/api/sheets/v4"
)

func main() {
        ctx := context.Background()

        c, err := getClient(ctx)
        if err != nil {
                log.Fatal(err)
        }

        sheetsService, err := sheets.New(c)
        if err != nil {
                log.Fatal(err)
        }

        // The ID of the spreadsheet to update.
        spreadsheetId := "1diQ943LGMDNkbCRGG4VqgKZdzyanCtT--V8o7r6kCR0"
        var jsonPayloadVar []string
        monthVar := "Apr"
        thisCellVar := "A26"
        thisLinkVar := "http://test.url"
        jsonRackNumberVar := "\"RACKNUM01\""
        jsonPayloadVar = append(jsonPayloadVar, fmt.Sprintf("(\"range\":     \"%v!%v\", \"values\": [[\"%v,%v)\"]]),", monthVar, thisCellVar, thisLinkVar,     jsonRackNumberVar))

        rb := &sheets.BatchUpdateValuesRequest{"ValueInputOption":     "USER_ENTERED", "data": jsonPayloadVar}
        resp, err :=     sheetsService.Spreadsheets.Values.BatchUpdate(spreadsheetId,     rb).Context(ctx).Do()
        if err != nil {
                log.Fatal(err)
        }

        fmt.Printf("%#v\n", resp)
}

func getClient(ctx context.Context) (*http.Client, error) {
        //     https://developers.google.com/sheets/quickstart/go#step_3_set_up_the_sample
        //
        // Authorize using the following scopes:
        //     sheets.DriveScope
        //     sheets.DriveFileScope
             sheets.SpreadsheetsScope
        return nil, errors.New("not implemented")
}

输出:

hello.go:43:结构初始化程序中的无效字段名称“ValueInputOption”
hello.go:43:结构初始化程序中的无效字段名称“数据”
hello.go:58:sheets.SpreadsheetsScope 已评估但未使用

有两件事不起作用:

  1. 如何将字段输入变量 rb 并不明显
  2. 我需要使用 sheet.SpreadsheetsScope

谁能提供一个执行 BatchUpdate 的工作示例?

参考资料:本文展示了如何进行不是 BatchUpdate 的更新:Golang google sheet API V4 - Write/Update example?

Google 的 API 参考 - 请参阅从第 1437 行开始的 ValueInputOption 部分:https ://github.com/google/google-api-go-client/blob/master/sheets/v4/sheets-gen.go

本文展示了如何在 Java 中执行 BatchUpdate:Write data to Google Sheet using Google Sheet API V4 - Java Sample Code

4

1 回答 1

4

下面的示例脚本怎么样?这是一个用于更新电子表格上的工作表的简单示例脚本。所以如果你想做各种更新,请修改它。电子表格.values.batchUpdate 的详细参数在这里

流动 :

首先,为了使用您问题中的链接,请使用Go Quickstart。在我的示例脚本中,该脚本是使用快速入门制作的。

使用此示例脚本的流程如下。

  1. 对于Go Quickstart,请执行步骤 1 和步骤 2。
  2. client_secret.json与我的示例脚本放在同一目录中。
  3. 复制并粘贴我的示例脚本,并将其创建为新的脚本文件。
  4. 运行脚本。
  5. Go to the following link in your browser then type the authorization code:显示在您的终端上时,请复制 URL 并粘贴到您的浏览器。然后,请授权并获取代码。
  6. 将代码放入终端。
  7. 显示时Done.,表示电子表格更新完成。

请求正文:

对于Spreadsheets.Values.BatchUpdate,BatchUpdateValuesRequest是必需的参数之一。在这种情况下,您要更新的范围、值等都包含在BatchUpdateValuesRequest. 这方面的详细信息BatchUpdateValuesRequest可以在godoc看到。当它看到时BatchUpdateValuesRequestData []*ValueRange可以看到。Data在这里,请小心[]*ValueRange。也ValueRange可以在godoc看到。你可以看到MajorDimensionRange并且ValuesValueRange

当上述信息反映到脚本中时,可以如下修改脚本。

示例脚本:

package main

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

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

// getClient uses a Context and Config to retrieve a Token
// then generate a Client. It returns the generated Client.
func getClient(ctx context.Context, config *oauth2.Config) *http.Client {
    cacheFile := "./go-quickstart.json"
    tok, err := tokenFromFile(cacheFile)
    if err != nil {
        tok = getTokenFromWeb(config)
        saveToken(cacheFile, tok)
    }
    return config.Client(ctx, tok)
}

// getTokenFromWeb uses Config to request a Token.
// It returns the retrieved Token.
func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {
    authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
    fmt.Printf("Go to the following link in your browser then type the "+
        "authorization code: \n%v\n", authURL)

    var code string
    if _, err := fmt.Scan(&code); err != nil {
        log.Fatalf("Unable to read authorization code %v", err)
    }

    tok, err := config.Exchange(oauth2.NoContext, code)
    if err != nil {
        log.Fatalf("Unable to retrieve token from web %v", err)
    }
    return tok
}

// tokenFromFile retrieves a Token from a given file path.
// It returns the retrieved Token and any read error encountered.
func tokenFromFile(file string) (*oauth2.Token, error) {
    f, err := os.Open(file)
    if err != nil {
        return nil, err
    }
    t := &oauth2.Token{}
    err = json.NewDecoder(f).Decode(t)
    defer f.Close()
    return t, err
}

func saveToken(file string, token *oauth2.Token) {
    fmt.Printf("Saving credential file to: %s\n", file)
    f, err := os.Create(file)
    if err != nil {
        log.Fatalf("Unable to cache oauth token: %v", err)
    }
    defer f.Close()
    json.NewEncoder(f).Encode(token)
}

type body struct {
    Data struct {
        Range  string     `json:"range"`
        Values [][]string `json:"values"`
    } `json:"data"`
    ValueInputOption string `json:"valueInputOption"`
}

func main() {
    ctx := context.Background()
    b, err := ioutil.ReadFile("client_secret.json")
    if err != nil {
        log.Fatalf("Unable to read client secret file: %v", err)
    }
    config, err := google.ConfigFromJSON(b, "https://www.googleapis.com/auth/spreadsheets")
    if err != nil {
        log.Fatalf("Unable to parse client secret file to config: %v", err)
    }
    client := getClient(ctx, config)
    sheetsService, err := sheets.New(client)
    if err != nil {
        log.Fatalf("Unable to retrieve Sheets Client %v", err)
    }

    spreadsheetId := "### spreadsheet ID ###"
    rangeData := "sheet1!A1:B3"
    values := [][]interface{}{{"sample_A1", "sample_B1"}, {"sample_A2", "sample_B2"}, {"sample_A3", "sample_A3"}}
    rb := &sheets.BatchUpdateValuesRequest{
        ValueInputOption: "USER_ENTERED",
    }
    rb.Data = append(rb.Data, &sheets.ValueRange{
        Range:  rangeData,
        Values: values,
    })
    _, err = sheetsService.Spreadsheets.Values.BatchUpdate(spreadsheetId, rb).Context(ctx).Do()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Done.")
}

结果 :

在此处输入图像描述

参考 :

  • 的详细信息spreadsheets.values.batchUpdate这里
  • Go Quickstart 的详细信息在这里
  • 的详细信息BatchUpdateValuesRequest这里
  • 的详细信息ValueRange这里

如果我误解了你的问题,我很抱歉。

于 2017-09-15T05:13:27.253 回答