简体   繁体   English

使用 golang 在 csv 文件中写入多列

[英]Writing multiple columns in a csv file using golang

I'm trying to write a CSV file, I can have 1 to n columns.我正在尝试编写一个 CSV 文件,我可以有 1 到 n 列。 Currently my data are correctly written except that they are all written on the same column.目前我的数据是正确写入的,只是它们都写在同一列上。

I would like to have something like this :我想要这样的东西:

NAME|DESCRIPTION|PRODUCER名称|描述|生产商
name1|desc1|false名称 1|desc1|假
name2|desc2|true名称2|描述2|真
name3|desc3|false名称3|desc3|假

Here is my code, a small piece of a switch:这是我的代码,一小部分开关:

    case "companies":
                var respToolCompanies entrepriseTool.CompaniesResponse
                if jsonErr := json.Unmarshal(resByt, &respToolCompanies); jsonErr != nil {
                    log.Fatalf("unmarshal: %s", jsonErr)
                }
                for _, mapping := range mappings {
                    writeHeader(csvwriter, mapping)

                    for _, company := range respToolCompanies.Companies {
                        writeDataAccordinglyToFieldType(mapping, company, csvwriter)
                    }
                    csvwriter.Flush()
                }

The writeDataAccordinglyToFieldType function: writeDataAccordinglyToFieldType 函数:

func writeDataAccordinglyToFieldType(mapping ExportmappingsModel, entities interface{}, csvwriter *csv.Writer) {
    switch mapping.SourceColType.String {
    case "string":
        field := extractFieldValue(entities, mapping)
        writeFieldToBuffer(csvwriter, field.String())
    case "number":
        field := extractFieldValue(entities, mapping)
        valInt := field.Int()
        str := strconv.Itoa(int(valInt))
        writeFieldToBuffer(csvwriter, str)
    case "bool":
        field := extractFieldValue(entities, mapping)
        var boolVal string
        if field.Bool() {
            boolVal = "true"
        } else {
            boolVal = "false"
        }
        writeFieldToBuffer(csvwriter, boolVal)
    }
}

And where I write data:我在哪里写数据:

func writeFieldToBuffer(csvwriter *csv.Writer, field string) {
    err := csvwriter.Write([]string{field})
    if err != nil {
        log.Println("Unable to write a line inside the file")
    }
}

csv.Write will write in different column only when your string slice will have multiple elements .Currently you are writing each field one by one and using a slice that is only having one record at one time csv.Write 仅当您的字符串切片将具有多个元素时才会写入不同的列。目前您正在逐个写入每个字段并使用一次只有一条记录的切片

I am not saying that you have to pass the delimiter .Rather populate the string slice all at once so that csv.Write automatically iterates over the slice and write each new element in new column.我并不是说您必须传递分隔符。而是一次填充字符串切片,以便 csv.Write 自动迭代切片并将每个新元素写入新列中。 . . So change your logic to change所以改变你的逻辑来改变

       err := csvwriter.Write([]string{field})

to something like this : enter code here像这样:在此处输入代码

  record := []string {"name1" ,"desc1","false"}
   if err := csvwriter.Write(record); err != nil {
          log.Fatalln("error writing record to file", err)
         }

or you can populate the whole thing using the two dimensional slice and then writeall at the end或者您可以使用二维切片填充整个内容,然后在最后写入

   records := [][]string {{"name1" ,"desc1","false"},{"name2" 
   ,"desc2","false"}}
     if err := csvwriter.WriteAll(records); err != nil {
            log.Fatalln("error writing record to file", err)
           }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM