我正在尝试将我的数据转换为 CSV。我非常接近。我现在遇到的问题是 CSV Writer 需要一个 [] 字符串。但我无法弄清楚如何将我的数据从结构中获取到一个 [] 字符串中。我正在循环我的 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 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
err = writer.Write(allData)
checkError("Cannot write to file...", err)
}
func checkError(message string, err error) {
if err != nil {
log.Fatal(message, err)
}
}
侃侃无极
相关分类