csv - 处理上传的 csv 文件

标签 csv go go-gin

我有一个 gin 应用程序,它接收一个包含 csv 文件的发布请求,我想读取该文件而不保存它。我被困在这里尝试从发布请求中读取以下错误消息: cannot use file (variable of type *multipart.FileHeader) as io.Reader value in argument to csv.NewReader: Missing method Read

file, err := c.FormFile("file")
if err != nil {
    errList["Invalid_body"] = "Unable to get request"
    c.JSON(http.StatusUnprocessableEntity, gin.H{
        "status": http.StatusUnprocessableEntity,
        "error":  errList,
    })
}

r := csv.NewReader(file) // <= Error message

records, err := r.ReadAll()

for _, record := range records {
    fmt.Println(record)
}

有一个我可以使用的好例子吗?

最佳答案

首先读取文件和头

csvPartFile, csvHeader, openErr := r.FormFile("file")
if openErr != nil {
    // handle error 
}

然后从文件中读取行

csvLines, readErr := csv.NewReader(csvPartFile).ReadAll()
if readErr != nil {
  //handle error 
}

您可以遍历记录中的行

for _, line := range csvLines {
        fmt.Println(line)
    }

关于csv - 处理上传的 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65992234/

相关文章:

go - 如何在 Gin 中间件中获取 url?

php - 加密 300 万条记录的最快方法

python - 如何确保 Pandas 不会将数字字符串解释为 Pandas 中的数字?

go - 从 mgo GridFile 中提取 Id 的字符串值

Golang 错误的http请求头

json - 如何使用 gin gonic 在 Go 中上传多部分文件和 json?

postgresql - 将 CSV 文件导入 PostgreSQL

javascript - Fast-csv 将所有内容写在一行中。需要多行输出

sql - 向 postgres 查询添加查询参数时出错

node.js - eclipse 车 : bash: gdb: command not found