csv 转换与 go

我仍然是golang的菜鸟,但我会尝试解释我想创造什么。

我有这个:

http://img.mukewang.com/62fa2ac90001a0cd06550393.jpg

我想将同一个表转换为csv文件,例如

http://img2.mukewang.com/62fa2ad60001005506570225.jpg

这是我的代码:


func maakCSVBestand() {


    rapportage := haalRapportage()

    opdrachten := rapportage.Opdrachten


    csvFile, err := os.Create("Rapportage Urenverantwoording.csv")


    if err != nil {

        fmt.Println(err)

    }

    defer csvFile.Close()


    writer := csv.NewWriter(csvFile)

    writer.Comma = ';'

    writer.Write([]string{"Datum", "Naam", "Aantal uren gewerkt", "Aantal deuren gemaakt", "Informatie"})

    for i := 0; i < len(opdrachten); i++ {


        var row []string

        persoon := opdrachten[i].Persoon

        row = append(row, opdrachten[i].Datum.String())


        for j := 0; j < len(persoon); j++ {


            row = append(row, persoon[j].Naam+" "+persoon[j].Achternaam)

            row = append(row, strconv.FormatFloat(persoon[j].UrenGewerkt, 'g', 2, 64))

            row = append(row, strconv.Itoa(persoon[j].AantalDeurenGemaakt))

            row = append(row, persoon[j].Informatie)


        }

        writer.Write(row)


    }

    writer.Flush()

}

但这会产生

http://img4.mukewang.com/62fa2ae70001386014740103.jpg

我做错了什么?


慕勒3428872
浏览 121回答 1
1回答

叮当猫咪

为内部循环的每次迭代写入一行。清除第一次迭代后的第一列:for i := 0; i < len(opdrachten); i++ {&nbsp; &nbsp; var row []string&nbsp; &nbsp; persoon := opdrachten[i].Persoon&nbsp; &nbsp; row = append(row, opdrachten[i].Datum.String())&nbsp; &nbsp; for j := 0; j < len(persoon); j++ {&nbsp; &nbsp; &nbsp; &nbsp; row = append(row, persoon[j].Naam+" "+persoon[j].Achternaam)&nbsp; &nbsp; &nbsp; &nbsp; row = append(row, strconv.FormatFloat(persoon[j].UrenGewerkt, 'g', 2, 64))&nbsp; &nbsp; &nbsp; &nbsp; row = append(row, strconv.Itoa(persoon[j].AantalDeurenGemaakt))&nbsp; &nbsp; &nbsp; &nbsp; row = append(row, persoon[j].Informatie)&nbsp; &nbsp; &nbsp; &nbsp; writer.Write(row)&nbsp; &nbsp; &nbsp; &nbsp; row[0] = ""&nbsp; &nbsp;// clear Datum field&nbsp; &nbsp; &nbsp; &nbsp; row = row[1:] // collect new values after blank datum&nbsp;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go