Home  >  Article  >  Backend Development  >  Convert structure to CSV string

Convert structure to CSV string

王林
王林forward
2024-02-09 15:15:251208browse

将结构转换为 CSV 字符串

php editor Youzi will introduce you how to convert the data structure into a CSV string in this article. CSV (Comma Separated Values) is a commonly used file format used to store tabular data. By converting the data structure into a CSV string, you can conveniently export the data to other tools such as Excel for processing and analysis. In this article, we will explore the methods and techniques to implement this process using the PHP programming language. Whether you are a beginner or an experienced developer, this article will provide you with helpful guidance and sample code to help you accomplish this task with ease.

Question content

I have a structure that is scanned after the database responds as shown below. Each field is the same len(). I want to take this structure and generate a csv delimited string/

package main

import "fmt"

type data struct {
    id   []string
    col1 []float64
    col2 []float64
}

func main() {
    d := &data{
        id:   []string{"id_1", "id_1", "id_1", "id_1"},
        col1: []float64{340.384926, 321.385028, 520.341473, 500.385473},
        col2: []float64{123.285031, 4087.284675, -8958.284216, -7612.283668},
    }
    fmt.printf("%+v", d)
}

I want to loop through a structure that I think I can use reflect and then use the structure field names as headers and the values ​​as the individual columns of that header to construct a csv string like the following, consisting of a separated by commas.

`
id,col1,col2
id_1,340.384926,123.285031
id_1,321.385028,4087.284675
id_1,520.341473,-8958.284216
id_1,500.385473,-7612.283668
`

What is an efficient way to achieve this?

Workaround

If possible, avoid using reflect iterating structures as it may cause performance degradation and code readability Reduced sex. Don't fall into the xy problem - the requirement here is to convert the data structure into a csv string (y problem), but the x problem here is to avoid using data etc. Structural types as a starting point.

Many golang packages that operate on csv prefer:

However, if the data type is unavoidable, you can first write a function to convert data to [][]string while avoiding reflect

func transformdatato2dslice(d data) [][]string {

    numrows := len(d.id)
    result := make([][]string, numrows+1)

    // add header row
    result[0] = []string{"id", "col1", "col2"}

    // add data rows
    for i := 0; i < numrows; i++ {
        result[i+1] = []string{d.id[i],
            strconv.formatfloat(d.col1[i], 'f', -1, 64),
            strconv.formatfloat(d.col2[i], 'f', -1, 64),
        }
    }

    return result
}

Next, use the w.writeall() method in encoding/csv to easily convert [][]string to csv

func main() {

    d := data{
        id:   []string{"id_1", "id_1", "id_1", "id_1"},
        col1: []float64{340.384926, 321.385028, 520.341473, 500.385473},
        col2: []float64{123.285031, 4087.284675, -8958.284216, -7612.283668},
    }

    d2dslice := transformdatato2dslice(d)

    // fmt.printf("%+v", d2dslice)
    // [[id, col1, col2],
    // [id_1, 340.384926, 123.285031],
    // [id_1, 321.385028, 4087.284675],
    // [id_1, 520.341473, -8958.284216],
    // [id_1,500.385473,-7612.283668]]

    w := csv.newwriter(os.stdout)
    w.writeall(d2dslice)

    if err := w.error(); err != nil {
        log.fatalln("error writing csv:", err)
    }

    // stdout:
    // id,col1,col2
    // id_1,340.384926,123.285031
    // id_1,321.385028,4087.284675
    // id_1,520.341473,-8958.284216
    // id_1,500.385473,-7612.283668
}

Run the above program here: go-playground

To write the csv to a string variable, pass in the buffer:

buf := new(bytes.Buffer)
    w := csv.NewWriter(buf)
    w.WriteAll(d2dslice)

    if err := w.Error(); err != nil {
        log.Fatalln("error writing csv:", err)
    }

    csvString := buf.String()

    fmt.Printf("%T\n", csvString)  // print the variable type
    // string

    fmt.Printf("%+v\n", csvString) // print the variable value
    // id,col1,col2
    // id_1,340.384926,123.285031
    // id_1,321.385028,4087.284675
    // id_1,520.341473,-8958.284216
    // id_1,500.385473,-7612.283668

The above is the detailed content of Convert structure to CSV string. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete