blob: 98878303bc48dc8bb40a7131f00d467018112621 [file] [log] [blame]
Anand S Katti09541352020-01-29 15:54:01 +05301// Copyright 2014 Oleku Konko All rights reserved.
2// Use of this source code is governed by a MIT
3// license that can be found in the LICENSE file.
4
5// This module is a Table Writer API for the Go Programming Language.
6// The protocols were written in pure Go and works on windows and unix systems
7
8package tablewriter
9
10import (
11 "encoding/csv"
12 "io"
13 "os"
14)
15
16// Start A new table by importing from a CSV file
17// Takes io.Writer and csv File name
18func NewCSV(writer io.Writer, fileName string, hasHeader bool) (*Table, error) {
19 file, err := os.Open(fileName)
20 if err != nil {
21 return &Table{}, err
22 }
23 defer file.Close()
24 csvReader := csv.NewReader(file)
25 t, err := NewCSVReader(writer, csvReader, hasHeader)
26 return t, err
27}
28
29// Start a New Table Writer with csv.Reader
30// This enables customisation such as reader.Comma = ';'
31// See http://golang.org/src/pkg/encoding/csv/reader.go?s=3213:3671#L94
32func NewCSVReader(writer io.Writer, csvReader *csv.Reader, hasHeader bool) (*Table, error) {
33 t := NewWriter(writer)
34 if hasHeader {
35 // Read the first row
36 headers, err := csvReader.Read()
37 if err != nil {
38 return &Table{}, err
39 }
40 t.SetHeader(headers)
41 }
42 for {
43 record, err := csvReader.Read()
44 if err == io.EOF {
45 break
46 } else if err != nil {
47 return &Table{}, err
48 }
49 t.Append(record)
50 }
51 return t, nil
52}