亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

GO 從結構中循環數據并將其轉換為字符串數組以生成 CSV

GO 從結構中循環數據并將其轉換為字符串數組以生成 CSV

Go
慕田峪7331174 2023-08-21 14:06:54
我正在嘗試將我的數據放入 CSV 中。我非常接近。我現在遇到的問題是 CSV 編寫器需要一個 [] 字符串。但我不知道如何將我的數據從結構中獲取到一個 [] 字符串中。我正在循環遍歷 json 數據并將其附加到創建一個新模型。如何讓我的模型被接受?import (    "encoding/csv"    "fmt"    "log"    "os"    "strconv"    "time"    "bitbucket.org/exzeo-usa/devops-aws-report/models")func CreateCSV(incidents models.IncidentModel) {    fmt.Println("Creating CSV...")    m := []models.EndModel{}    for i := range incidents.Incidents {        m = append(m, models.EndModel{            IncidentNumber: strconv.Itoa(incidents.Incidents[i].IncidentNumber),            Title:          incidents.Incidents[i].Title,            CreatedAt:      incidents.Incidents[i].CreatedAt,            Notes:          GetNotes(incidents.Incidents[i].IncidentNumber),        })    }    fmt.Print(m)    writeCSV(m)    return}//writeCSV is a function create a .csv filefunc writeCSV(allData []models.EndModel) {    today := time.Now().Format("2006-01-02")    fileString := fmt.Sprintf("result-%v.csv", today)    //Create File    file, err := os.Create(fileString)    checkError("Cannot create file", err)    defer file.Close()    //Create the writer with the file    writer := csv.NewWriter(file)    defer writer.Flush()    //Create and Write to the CSV    err = writer.Write(allData)    checkError("Cannot write to file...", err)}func checkError(message string, err error) {    if err != nil {        log.Fatal(message, err)    }}
查看完整描述

1 回答

?
慕妹3242003

TA貢獻1824條經驗 獲得超6個贊

一般來說,您不能簡單地從一種類型映射到另一種類型并讓編譯器弄清楚如何轉換數據。其他語言可能會提供一些語法糖或有一些推斷合理默認值的先例,但 Go 故意不提供這種魔力。


您需要明確指示如何將數據結構的每個實例轉換為要作為 CSV 行寫出models.EndModel的切片。[]string


像下面這樣:


// writeCSV is a function create a .csv file

func writeCSV(allData []models.EndModel) {


    today := time.Now().Format("2006-01-02")

    fileString := fmt.Sprintf("result-%v.csv", today)


    //Create File

    file, err := os.Create(fileString)

    checkError("Cannot create file", err)

    defer file.Close()


    // Create the writer with the file

    writer := csv.NewWriter(file)

    defer writer.Flush()


    // Create and Write to the CSV

    csvRows := make([][]string, len(allData))

    for i, model := range allData {

        csvRows[i] = []string{

            // Choose the ordering you wish in your output CSV

            model.IncidentNumber,

            model.Title,

            model.CreatedAt,

            model.Notes,

        }

    }


    // Note that you need to call WriteAll to pass multiple rows

    err = writer.WriteAll(csvRows)

    checkError("Cannot write to file...", err)


}


查看完整回答
反對 回復 2023-08-21
  • 1 回答
  • 0 關注
  • 186 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號