将CSV内容转换为Go界面以将其上传到Google表格

I am trying to send the contents of a CSV file to a Google Sheet, via their very ill-documented API for Go.

The BatchUpdate takes an interface, so this would work:

values := [][]interface{}{{"one cell", "another cell"}, {"one cell in new row", "another cell in new row"}}

The problem comes when I want to send the contents from a CSV. I have done this:

func prepare(filename string) [][]interface{} {

    file, _ := os.Open(filename)

    defer file.Close()

    reader := csv.NewReader(file)
    record, err := reader.ReadAll()
    if err != nil {
        fmt.Println("Error", err)
    }

    all := [][]interface{}{}

    for _, value := range record {
        all = append(all, []interface{}{value})
    }

    return all
}

And I believe this should give me the interface ready to be inserted in the sheet. However, when I do this later on:

rb := &sheets.BatchUpdateValuesRequest{
        ValueInputOption: "USER_ENTERED",
    }
    rb.Data = append(rb.Data, &sheets.ValueRange{
        Range:  rangeData,
        Values: values, // This is the interface that I returned earlier on
    })
    _, err = sheetsService.Spreadsheets.Values.BatchUpdate(spreadsheetId, rb).Context(ctx).Do() 

it gives me a googleapi: Error 400: Invalid data[0]: Invalid values[0][0]

So I understand that I am trying to pass the CSV fields in an incorrect format. I know that when I do this in Python, I need to pass it as tuples for the data to be accepted. What's the correct way to pass the data here in Go?

查看全部
doujia1904
doujia1904
2018/02/11 11:00
  • csv
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复