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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题