GoCSV包:一个能将结构体和csv文件直接互转的工具
大家在开发中一定遇到过将数据导出成csv格式文件的需求。go标准库中的csv包是只能写入字符串类型的切片。而在go中一般都是以结构体为操作对象,若使用标准的csv包,就需要将结构体先转换成对应的字符串类型,再写入文件。 那可不可以将结构体对象直接输出成csv格式内容呢?
今天给大家推荐的就是一个能将结构体和csv内容进行快速互转的工具包:gocsv
1. gocsv小档案
| gocsv 小档案 | |
|---|---|
| star | 1.5 k |
| used by | 1.6k |
| contributors | 80 |
| 作者 | gocarina |
| 功能简介 | 提供一个简单、高效地将csv内容和结构体进行互转的功能 |
| 项目地址 | https://github.com/gocarina/gocsv |
| 相关知识 | reflect、结构体tag |
1.1. gocsv的基本功能
gocsv包的最基本的作用就是能够方便的将csv内容转换到对应的结构体上,或者将结构体的内容快速的转换成csv格式(包括写入文件)。
1.2. gocsv.UnmarshalFile函数:csv内容转成结构体
假设文件中的内容如下:
1client_id,client_name,client_age
21,Jose,42
32,Daniel,26
43,Vincent,32
然后从文件中读取出内容,并直接转换到结构体Client上,如下:
1package main
2
3import (
4 "fmt"
5 "os"
6
7 "github.com/gocarina/gocsv"
8)
9
10type NotUsed struct {
11 Name string
12}
13
14type Client struct { // Our example struct, you can use "-" to ignore a field
15 Id string `csv:"client_id"`
16 Name string `csv:"client_name"`
17 Age string `csv:"client_age"`
18 NotUsedString string `csv:"-"`
19 NotUsedStruct NotUsed `csv:"-"`
20}
21
22func main() {
23 clientsFile, err := os.OpenFile("clients.csv", os.O_RDWR|os.O_CREATE, os.ModePerm)
24 if err != nil {
25 panic(err)
26 }
27 defer clientsFile.Close()
28
29 clients := []*Client{}
30
31 if err := gocsv.UnmarshalFile(clientsFile, &clients); err != nil { // Load clients from file
32 panic(err)
33 }
34 for _, client := range clients {
35 fmt.Println("Hello", client.Name)
36 }
37}
1.3. gocsv.MarshalFile函数:结构体转成csv文件
1package main
2
3import (
4 "fmt"
5 "os"
6
7 "github.com/gocarina/gocsv"
8)
9
10type NotUsed struct {
11 Name string
12}
13
14type Client struct { // Our example struct, you can use "-" to ignore a field
15 Id string `csv:"client_id"`
16 Name string `csv:"client_name"`
17 Age string `csv:"client_age"`
18 NotUsedString string `csv:"-"`
19 NotUsedStruct NotUsed `csv:"-"`
20}
21
22func main() {
23 clientsFile, err := os.OpenFile("clients.csv", os.O_RDWR|os.O_CREATE, os.ModePerm)
24 if err != nil {
25 panic(err)
26 }
27 defer clientsFile.Close()
28
29 clients := []*Client{}
30
31 clients = append(clients, &Client{Id: "12", Name: "John", Age: "21"}) // Add clients
32 clients = append(clients, &Client{Id: "13", Name: "Fred"})
33 clients = append(clients, &Client{Id: "14", Name: "James", Age: "32"})
34 clients = append(clients, &Client{Id: "15", Name: "Danny"})
35
36 err = gocsv.MarshalFile(&clients, clientsFile) // Use this to save the CSV back to the file
37 if err != nil {
38 panic(err)
39 }
40
41}
1.4. 自定义类型转换器
gocsv包还可以给自定义的结构体类型定义csv和结构体的互转函数。只要自定义的类型实现如下接口即可:
1type TypeMarshaller interface {
2 MarshalCSV() (string, error)
3}
4
5// TypeUnmarshaller is implemented by any value that has an UnmarshalCSV method
6// This converter is used to convert a string to your value representation of that string
7type TypeUnmarshaller interface {
8 UnmarshalCSV(string) error
9}
或者将结构体转换成csv字符串时,需要实现如下接口:
1// MarshalText encodes the receiver into UTF-8-encoded text and returns the result.
2type TextMarshaler interface {
3 MarshalText() (text []byte, err error)
4}
5
6type TextUnmarshaler interface {
7 UnmarshalText(text []byte) error
8}
例如,我们定义了一个结构体DateTime,里面有一个time.Time类型的属性。并且DateTime类型实现了TypeMarshaller接口的MarshalCSV函数和TypeUnmarshaller接口的UnmarshalCSV函数。如下:
1type DateTime struct {
2 time.Time
3}
4
5// Convert the internal date as CSV string
6func (date *DateTime) MarshalCSV() (string, error) {
7 return date.Time.Format("20060201"), nil
8}
9
10// You could also use the standard Stringer interface
11func (date *DateTime) String() (string) {
12 return date.String() // Redundant, just for example
13}
14
15// Convert the CSV string as internal date
16func (date *DateTime) UnmarshalCSV(csv string) (err error) {
17 date.Time, err = time.Parse("20060201", csv)
18 return err
19}
20
21type Client struct { // Our example struct with a custom type (DateTime)
22 Id string `csv:"id"`
23 Name string `csv:"name"`
24 Employed DateTime `csv:"employed"`
25}
26
27func main() {
28
29 client := []Client{
30 {
31 Id: "001",
32 Name: "Go学堂",
33 Employed: DateTime{time.Now()},
34 },
35 }
36
37 csvContent, _ := gocsv.MarshalString(client)
38 fmt.Println("csv:", csvContent) //输出内容是 001,Go学堂,20231003
39}
当我们运行上述代码,最终的输出内容是:
1001,xzeu,20231003
最后的日期就是按DateTime的MarshalCSV函数格式输出的。
1.5. 自定义CSV的Reader/Writer
在开头处我们提到,csv文件中的分隔符默认是逗号。但也可以是其他字符。这就要求我们在读取或写入之前指定好内容的分隔号。那么就可以通过自定义的Reader/Writer来覆盖默认的Reader/Writer的选项。如下:
- 指定读取内容的分割符是 “|”
1gocsv.SetCSVReader(func(in io.Reader) gocsv.CSVReader {
2 r := csv.NewReader(in)
3 r.Comma = '|'
4 return r // Allows use pipe as delimiter
5})
- 指定写入的内容是用 分割符 “|” 进行分割的
1gocsv.SetCSVWriter(func(out io.Writer) *gocsv.SafeCSVWriter {
2 writer := csv.NewWriter(out)
3 writer.Comma = '|'
4 return gocsv.NewSafeCSVWriter(writer)
5})
1.6. gocsv包的特点总结
- 结构体切片和csv内容互转。能够将结构体切片(或数组)直接输出成csv内容或输出到文件。反之亦然。
- csv标签。其转换过程是通过结构体上的“csv”标签进行关联的。
- csv标签对应csv内容表头。当结构体和csv格式互转时,结构体中的csv标签对应的就是csv表格的表头,结构体中的字段顺序对应的就是csv文件列的顺序。
- 底层依然是使用标准库中的csv。在写入csv文件时,底层实际上用的还是go标准库中的encoding/csv/Writer结构体的Write(row []string)方法。
- 自动将结构体字段的类型转换成字符串:大家看到标准csv包中的Write方法的入参是string类型的切片,而在要转换的结构体上的字段可以是各种类型。这里就是gocsv包中的一个特点:可以将字段中的非string类型转换成string类型,最终写入到csv文件中。
- 可自定义类型转换器。可以通过实现TypeMarshaller接口或TypeUnMarshaller接口对自定义类型的内容按对应的格式输出成csv内容。
- 可自定义CSV的Reader/Writer来覆盖默认参数。比如csv格式的内容默认使用逗号分隔内容。通过该功能我们可以指定使用其他分隔符的csv内容。比如使用"|“或”;“等。 这里需要注意的是 将csv文件的内容一定是解析到结构体类型的切片或数组中。同样,也只有是结构体类型的切片或数组才能直接写入到csv文件中。