How to create a NamgedRange using google sheets API when doing a batch update with Go

huangapple go评论75阅读模式
英文:

How to create a NamgedRange using google sheets API when doing a batch update with Go

问题

我最近开始编写一个程序,用于将CSV和SQL导出到Google Sheets。在某些情况下,我需要在创建表格和/或更新表格时创建一个命名范围。Google官方文档有点混乱,对我来说帮助不大。有人可以给我展示一个示例代码或指点我正确的方向吗?

目前我有以下代码。这只是一个示例代码,展示了其中一种情况。

    func writeSS(ssid string, content [][]interface{}) {

	ctx := context.Background()

	b, err := ioutil.ReadFile("./credentials/client_secret.json")
	if err != nil {
		log.Fatalf("无法读取客户端密钥文件:%v", err)
	}

	config, err := google.ConfigFromJSON(b, "https://www.googleapis.com/auth/spreadsheets.readonly")
	if err != nil {
		log.Fatalf("无法将客户端密钥文件解析为配置:%v", err)
	}
	client := getClient(config)

	srv, err := sheets.NewService(ctx, option.WithHTTPClient(client))
	if err != nil {
		log.Fatalf("无法获取Sheets客户端:%v", err)
	}

	spreadsheetId := ssid

	rangeData := "表格名称!A1:A6"

	rb := &sheets.BatchUpdateValuesRequest{
		ValueInputOption: "USER_ENTERED",
	}

	rb.Data = append(rb.Data, &sheets.ValueRange{
		Range:  rangeData,
		Values: content,
	})
	_, err = srv.Spreadsheets.Values.BatchUpdate(spreadsheetId, rb).Context(ctx).Do() //再次检查此处
	// _, err = srv.Spreadsheets.Values.Update(spreadsheetId, writeRange, &vr).ValueInputOption("USER_ENTERED").Do()

	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("完成。")
}
英文:

I recently started writing a program to export CSV and SQL to google sheets. And in some scenarios I need to create a NamedRange while creating the sheet and/or updating it. The google official documentation is kinda confusion and not very helpful for me. Can anyone please show me an example code or point me in the right direction?

Right now I have something along these lines. This is just sample code to show one of the scenarios.

    func writeSS(ssid string, content [][]interface{}) {

	ctx := context.Background()

	b, err := ioutil.ReadFile("./credentials/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.readonly")
	if err != nil {
		log.Fatalf("Unable to parse client secret file to config: %v", err)
	}
	client := getClient(config)

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

	spreadsheetId := ssid

	rangeData := "Sheet name!A1:A6"

	rb := &sheets.BatchUpdateValuesRequest{
		ValueInputOption: "USER_ENTERED",
	}

	rb.Data = append(rb.Data, &sheets.ValueRange{
		Range:  rangeData,
		Values: content,
	})
	_, err = srv.Spreadsheets.Values.BatchUpdate(spreadsheetId, rb).Context(ctx).Do() //Check this again
	// _, err = srv.Spreadsheets.Values.Update(spreadsheetId, writeRange, &vr).ValueInputOption("USER_ENTERED").Do()

	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Done.")
}

答案1

得分: 1

我相信你的目标如下:

  • 你想使用Googleapis和Golang创建一个命名范围。
  • 你已经能够使用Sheets API获取和放置Google电子表格的值。

修改点:

  • 当我看到你的脚本时,使用了Sheets API的spreadsheets.values.batchUpdate方法。当你想在现有的Google电子表格中创建命名范围时,请使用spreadsheets.batchUpdate方法。
  • 在你的脚本中,你试图使用https://www.googleapis.com/auth/spreadsheets.readonly的范围将值放置到单元格中。我认为与范围相关的错误会发生。在这种情况下,请使用https://www.googleapis.com/auth/spreadsheets的范围。

当这些点反映在你的脚本中时,它变成了以下内容:

修改后的脚本:

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(config)

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

spreadsheetId := "###" // 请设置你的电子表格ID。
sheetId := 1234567890 // 请设置你的工作表ID。
nameOfNamedRange := "sampleNamedRange1" // 请设置命名范围的名称。

req := sheets.Request{
	AddNamedRange: &sheets.AddNamedRangeRequest{
		NamedRange: &sheets.NamedRange{
			Range: &sheets.GridRange{
				SheetId:          int64(sheetId),
				StartRowIndex:    1,
				EndRowIndex:      3,
				StartColumnIndex: 1,
				EndColumnIndex:   3,
			},
			Name: nameOfNamedRange,
		},
	},
}
requestBody := &sheets.BatchUpdateSpreadsheetRequest{
	Requests: []*sheets.Request{&req},
}
resp, err := srv.Spreadsheets.BatchUpdate(spreadsheetId, requestBody).Do()
if err != nil {
	log.Fatal(err)
}
fmt.Print(resp)
  • 在这个示例脚本中,StartRowIndex: 1, EndRowIndex: 3, StartColumnIndex: 1, EndColumnIndex: 3的gridrange表示单元格"B2:C3"。
  • 当运行此脚本时,将在spreadsheetId的Google电子表格中的sheetId的"B2:C3"范围创建名为nameOfNamedRange的命名范围。

注意:

  • 根据你展示的脚本,不幸的是,我无法知道包含访问令牌和刷新令牌的文件的文件名。如果文件名是快速入门中使用的token.json,在运行修改后的脚本之前,请删除该文件。然后,请重新授权范围。请注意这一点。

参考资料:

英文:

I believe your goal is as follows.

  • You want to create a named range using googleapis with golang.
  • You have already been able to get and put values for Google Spreadsheet using Sheets API.

Modification points:

  • When I saw your script, the method of spreadsheets.values.batchUpdate of Sheets API is used. When you want to create the named range in the existing Google Spreadsheet, please use the method of spreadsheets.batchUpdate.
  • In your script, you are trying to put the values to the cells using the scope of https://www.googleapis.com/auth/spreadsheets.readonly. I think that an error related to the scopes occurs. In this case, please use the scope of https://www.googleapis.com/auth/spreadsheets.

When these points are reflected in your script, it becomes as follows.

Modified script:

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(config)

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

spreadsheetId := "###" // Please set your Spreadsheet ID.
sheetId := 1234567890 // Please set your sheet ID.
nameOfNamedRange := "sampleNamedRange1" // Please set the name of the named range.

req := sheets.Request{
	AddNamedRange: &sheets.AddNamedRangeRequest{
		NamedRange: &sheets.NamedRange{
			Range: &sheets.GridRange{
				SheetId:          int64(sheetId),
				StartRowIndex:    1,
				EndRowIndex:      3,
				StartColumnIndex: 1,
				EndColumnIndex:   3,
			},
			Name: nameOfNamedRange,
		},
	},
}
requestBody := &sheets.BatchUpdateSpreadsheetRequest{
	Requests: []*sheets.Request{&req},
}
resp, err := srv.Spreadsheets.BatchUpdate(spreadsheetId, requestBody).Do()
if err != nil {
	log.Fatal(err)
}
fmt.Print(resp)
  • In this sample script, the gridrange of StartRowIndex: 1, EndRowIndex: 3, StartColumnIndex: 1, EndColumnIndex: 3, means the cells "B2:C3".
  • When this script is run, the named range of nameOfNamedRange is created with the range of "B2:C3" of sheetId in the Google Spreadsheet of spreadsheetId.

Note:

  • From your showing script, unfortunately, I cannot know the filename of the file including the access token and refresh token. If the filename is token.json used in the Quickstart, before you run the modified script, please delete the file. And, please reauthorize the scopes. Please be careful about this.

References:

huangapple
  • 本文由 发表于 2021年11月1日 08:39:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/69791659.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定