csv.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // 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. // This module is a Table Writer API for the Go Programming Language.
  5. // The protocols were written in pure Go and works on windows and unix systems
  6. package tablewriter
  7. import (
  8. "encoding/csv"
  9. "io"
  10. "os"
  11. )
  12. // Start A new table by importing from a CSV file
  13. // Takes io.Writer and csv File name
  14. func NewCSV(writer io.Writer, fileName string, hasHeader bool) (*Table, error) {
  15. file, err := os.Open(fileName)
  16. if err != nil {
  17. return &Table{}, err
  18. }
  19. defer file.Close()
  20. csvReader := csv.NewReader(file)
  21. t, err := NewCSVReader(writer, csvReader, hasHeader)
  22. return t, err
  23. }
  24. // Start a New Table Writer with csv.Reader
  25. // This enables customisation such as reader.Comma = ';'
  26. // See http://golang.org/src/pkg/encoding/csv/reader.go?s=3213:3671#L94
  27. func NewCSVReader(writer io.Writer, csvReader *csv.Reader, hasHeader bool) (*Table, error) {
  28. t := NewWriter(writer)
  29. if hasHeader {
  30. // Read the first row
  31. headers, err := csvReader.Read()
  32. if err != nil {
  33. return &Table{}, err
  34. }
  35. t.SetHeader(headers)
  36. }
  37. for {
  38. record, err := csvReader.Read()
  39. if err == io.EOF {
  40. break
  41. } else if err != nil {
  42. return &Table{}, err
  43. }
  44. t.Append(record)
  45. }
  46. return t, nil
  47. }