-
Notifications
You must be signed in to change notification settings - Fork 13
/
csv.go
76 lines (65 loc) · 1.52 KB
/
csv.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package exporter
import (
"bytes"
"encoding/csv"
"os"
)
type ICSVExporter interface {
exportToFile(columns []string, rows [][]interface{}, filePath string) error
exportToByte(columns []string, rows [][]interface{}) ([]byte, error)
}
type CSVExporter struct {
}
func NewCSVExportService() *CSVExporter {
return &CSVExporter{}
}
func (e *CSVExporter) exportToFile(columns []string, rows [][]interface{}, filePath string) error {
f, err := os.Create(filePath)
if err != nil {
return err
}
defer func(f *os.File) {
err := f.Close()
if err != nil {
panic(err.Error())
}
}(f)
writer := csv.NewWriter(f)
defer writer.Flush()
return e.export(writer, columns, rows)
}
func (e *CSVExporter) exportToByte(columns []string, rows [][]interface{}) ([]byte, error) {
err := verifyRows(columns, rows)
if err != nil {
return nil, err
}
var buf bytes.Buffer
writer := csv.NewWriter(&buf)
defer writer.Flush()
err = e.export(writer, columns, rows)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func (e *CSVExporter) export(writer *csv.Writer, columns []string, rows [][]interface{}) error {
record := make([]string, 0)
record = append(record, columns...)
err := writer.Write(record)
if err != nil {
panic(err.Error())
}
record = make([]string, 0)
for _, row := range rows {
for columnIndex := range columns {
record = append(record, row[columnIndex].(string))
}
err := writer.Write(record)
if err != nil {
panic(err.Error())
}
record = make([]string, 0)
}
writer.Flush()
return nil
}