谷歌表格 API : golang BatchUpdateValuesRequest

标签 go google-sheets-api google-api-go-client

我正在尝试按照此处的 Google Sheets API 快速入门:

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

(向下滚动到“Examples”,然后单击“GO”)

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

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: struct initializer 中的字段名称“ValueInputOption”无效
hello.go:43: struct initializer 中无效的字段名称“data”
hello.go:58: sheets.SpreadsheetsScope 已评估但未使用

有两件事不起作用:

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

任何人都可以提供一个执行 BatchUpdate 的工作示例吗?

引用资料: 本文介绍如何执行非 BatchUpdate 的更新:Golang google sheets 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

最佳答案

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

流程:

首先,为了使用 link在你的问题中,请使用 Go Quickstart .在我的示例脚本中,脚本是使用 Quickstart 创建的。

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

  1. Go Quickstart ,请执行第 1 步和第 2 步。
  2. 请将 client_secret.json 与我的示例脚本放在同一目录中。
  3. 复制并粘贴我的示例脚本,并将其创建为新的脚本文件。
  4. 运行脚本。
  5. 在您的浏览器中转到以下链接,然后键入授权代码: 显示在您的终端上时,请复制该 URL 并粘贴到您的浏览器。然后,请授权并获取代码。
  6. 将代码输入终端。
  7. 当显示Done.时,表示电子表格更新完成。

请求正文:

对于 Spreadsheets.Values.BatchUpdate,需要将 BatchUpdateValuesRequest 作为参数之一。在这种情况下,您要更新的范围、值等都包含在 BatchUpdateValuesRequest 中。这个BatchUpdateValuesRequest的详细信息可以在godoc看到.当它看到 BatchUpdateValuesRequest 时,可以看到 Data []*ValueRange。在这里,请注意 Data[]*ValueRangeValueRange 也可以在 godoc 处看到.您可以在 ValueRange 中看到 MajorDimensionRangeValues

当上述信息反射(reflect)到脚本中时,脚本可以修改如下。

示例脚本:

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.")
}

结果:

enter image description here

引用文献:

  • spreadsheets.values.batchUpdate 的详细信息是here .
  • Go Quickstart 的详细信息是here .
  • BatchUpdateValuesRequest 的详细信息是 here .
  • ValueRange 的详细信息是here .

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

关于谷歌表格 API : golang BatchUpdateValuesRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46230624/

相关文章:

javascript - 如何在 Google 脚本编辑器之外访问定义的函数?

git - 如何 fork 和修改 Google API Go 客户端 SDK 以解决 Slides API Range 问题?

bash - 安装 json2csv 时出现 $GOPATH 错误

bash - 从带有空格的脚本导出环境变量

string - Primitive.ObjectID 到 Golang 中的字符串

javascript - Google Sheets API 与 Ionic

java - 获取和更新单个谷歌工作表中的单元格(电子表格中的特定工作表)

go - 如何从 google-api-go-client 将日程设置到 Google 日历?

: bulk Get operation example