将 CSV 内容转换为 Go 接口以将它们上传到 Google Sheet

Convert CSV contents to Go interface to upload them to a Google Sheet

我正在尝试通过他们非常不完善的 API for Go 将 CSV 文件的内容发送到 Google Sheet。

BatchUpdate 需要一个 interface,所以这会起作用:

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

当我想从 CSV 发送内容时出现问题。我这样做了:

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
}

而且我相信这应该让我准备好将 interface 插入到 sheet 中。但是,当我稍后这样做时:

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

它给了我一个 googleapi: Error 400: Invalid data[0]: Invalid values[0][0]

据我所知,我正在尝试以错误的格式传递 CSV 字段。我知道当我在 Python 中执行此操作时,我需要将其作为元组传递,以便接受数据。在 Go 中传递数据的正确方法是什么?

我刚刚发现我的问题是什么,在追加时,我是这样做的:

all = append(all, []interface{}{value})

我应该这样做

all = append(all, []interface{}{value[0], value[1]})

这是因为value可以被索引,因为里面的每一项都对应一个单元格,所以我的CSV特意有两个单元格。只传递 value 是错误的格式。