Golang从表单读取CSV数据、进行分析并返回结果的方法

Golang从表单读取CSV数据、进行分析并返回结果的方法 你好,

我有一个CSV文件。我想通过一个HTML表单读取该文件,然后运行一些计算并将结果返回到表单中。有人能帮忙吗?

我尝试了使用Go上传文件 - YouTube

但是,我无法将CSV文件作为CSV文件进行计算,因为它被作为文本文件、作为字符串读取。

3 回复

谢谢。我会尝试。

更多关于Golang从表单读取CSV数据、进行分析并返回结果的方法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


你好,

你完全可以创建一个结构体映射——基于你CSV文件的列。 将结构体的特定属性转换为不同的数据类型,例如整数或浮点数, 然后对这个结构体映射进行计算。

可以使用 encoding/csv 包来解析CSV数据。以下是一个示例,展示如何从表单读取CSV文件、解析数据并返回分析结果:

package main

import (
    "encoding/csv"
    "fmt"
    "html/template"
    "net/http"
    "strings"
)

func main() {
    http.HandleFunc("/", uploadHandler)
    http.HandleFunc("/upload", uploadFileHandler)
    http.ListenAndServe(":8080", nil)
}

func uploadHandler(w http.ResponseWriter, r *http.Request) {
    tmpl := `
    <!DOCTYPE html>
    <html>
    <body>
        <form action="/upload" method="post" enctype="multipart/form-data">
            <input type="file" name="csvfile" accept=".csv">
            <input type="submit" value="上传并分析">
        </form>
    </body>
    </html>`
    t, _ := template.New("upload").Parse(tmpl)
    t.Execute(w, nil)
}

func uploadFileHandler(w http.ResponseWriter, r *http.Request) {
    if r.Method != "POST" {
        http.Error(w, "方法不允许", http.StatusMethodNotAllowed)
        return
    }

    file, header, err := r.FormFile("csvfile")
    if err != nil {
        http.Error(w, "无法读取文件", http.StatusBadRequest)
        return
    }
    defer file.Close()

    reader := csv.NewReader(file)
    records, err := reader.ReadAll()
    if err != nil {
        http.Error(w, "CSV解析失败", http.StatusBadRequest)
        return
    }

    // 示例分析:计算行数和列数
    rowCount := len(records)
    colCount := 0
    if rowCount > 0 {
        colCount = len(records[0])
    }

    // 示例分析:计算第一列数值总和(假设为数字)
    sum := 0
    for i, row := range records {
        if i == 0 {
            continue // 跳过标题行(如果有)
        }
        if len(row) > 0 {
            var val int
            fmt.Sscanf(row[0], "%d", &val)
            sum += val
        }
    }

    // 返回结果
    result := fmt.Sprintf("文件: %s<br>行数: %d<br>列数: %d<br>第一列总和: %d", 
        header.Filename, rowCount, colCount, sum)
    
    w.Header().Set("Content-Type", "text/html")
    fmt.Fprintf(w, "<h3>分析结果</h3><p>%s</p>", result)
}

这个示例包含以下功能:

  1. 显示文件上传表单
  2. 接收CSV文件上传
  3. 使用csv.NewReader解析CSV数据
  4. 执行简单的数据分析(计算行数、列数和第一列总和)
  5. 将分析结果以HTML格式返回

要运行此代码:

go run main.go

然后在浏览器中访问 http://localhost:8080 即可测试文件上传功能。

回到顶部