doujia1904 2018-02-11 11:00
浏览 33
已采纳

将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?

  • 写回答

1条回答 默认 最新

  • doujichan1399 2018-02-11 11:50
    关注

    I just found out what my problem was, when appending, I was doing this:

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

    And I should have done this

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

    This is, because value can be indexed, since every item inside of it corresponds to a cell, so my CSV specifically had two cells. Passing just value was the wrong format for this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏