-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathtablib_csv.go
81 lines (65 loc) · 1.57 KB
/
tablib_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
77
78
79
80
81
package tablib
import (
"bytes"
"encoding/csv"
)
// CSV returns a CSV representation of the Dataset an Exportable.
func (d *Dataset) CSV() (*Exportable, error) {
records := d.Records()
b := newBuffer()
w := csv.NewWriter(b)
w.WriteAll(records) // calls Flush internally
if err := w.Error(); err != nil {
return nil, err
}
return newExportable(b), nil
}
// LoadCSV loads a Dataset by its CSV representation.
func LoadCSV(input []byte) (*Dataset, error) {
reader := csv.NewReader(bytes.NewReader(input))
records, err := reader.ReadAll()
if err != nil {
return nil, err
}
ds := NewDataset(records[0])
for i := 1; i < len(records); i++ {
// this is odd
row := make([]interface{}, len(records[i]))
for k, v := range records[i] {
row[k] = v
}
ds.Append(row)
}
return ds, nil
}
// TSV returns a TSV representation of the Dataset as string.
func (d *Dataset) TSV() (*Exportable, error) {
records := d.Records()
b := newBuffer()
w := csv.NewWriter(b)
w.Comma = '\t'
w.WriteAll(records) // calls Flush internally
if err := w.Error(); err != nil {
return nil, err
}
return newExportable(b), nil
}
// LoadTSV loads a Dataset by its TSV representation.
func LoadTSV(input []byte) (*Dataset, error) {
reader := csv.NewReader(bytes.NewReader(input))
reader.Comma = '\t'
records, err := reader.ReadAll()
if err != nil {
return nil, err
}
ds := NewDataset(records[0])
for i := 1; i < len(records); i++ {
// this is odd
row := make([]interface{}, len(records[i]))
for k, v := range records[i] {
row[k] = v
}
ds.Append(row)
}
return ds, nil
}