forked from olekukonko/tablewriter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
csv.go
53 lines (47 loc) · 1.27 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
// Copyright 2014 Oleku Konko All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.
// This module is a Table Writer API for the Go Programming Language.
// The protocols were written in pure Go and works on windows and unix systems
package tablewriter
import (
"encoding/csv"
"fmt"
"io"
"os"
)
// Start A new table by importing from a CSV file
// Takes io.Writer and csv File name
func NewCSV(writer io.Writer, fileName string) (*table, error) {
file, err := os.Open(fileName)
if err != nil {
fmt.Println("Error:", err)
return &table{}, err
}
defer file.Close()
csvReader := csv.NewReader(file)
t, err := NewCSVReader(writer, csvReader)
return t, err
}
// Start a New Table Writer with csv.Reader
// This enables customisation such as reader.Comma = ';'
// See http://golang.org/src/pkg/encoding/csv/reader.go?s=3213:3671#L94
func NewCSVReader(writer io.Writer, csvReader *csv.Reader) (*table, error) {
// Read the first row
headers, err := csvReader.Read()
if err != nil {
return &table{}, err
}
t := NewWriter(writer)
t.SetHeader(headers)
for {
record, err := csvReader.Read()
if err == io.EOF {
break
} else if err != nil {
return &table{}, err
}
t.Append(record)
}
return t, nil
}