tablib_csv.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package tablib
  2. import (
  3. "bytes"
  4. "encoding/csv"
  5. )
  6. // CSV returns a CSV representation of the Dataset an Exportable.
  7. func (d *Dataset) CSV() (*Exportable, error) {
  8. records := d.Records()
  9. b := newBuffer()
  10. w := csv.NewWriter(b)
  11. w.WriteAll(records) // calls Flush internally
  12. if err := w.Error(); err != nil {
  13. return nil, err
  14. }
  15. return newExportable(b), nil
  16. }
  17. // LoadCSV loads a Dataset by its CSV representation.
  18. func LoadCSV(input []byte) (*Dataset, error) {
  19. reader := csv.NewReader(bytes.NewReader(input))
  20. records, err := reader.ReadAll()
  21. if err != nil {
  22. return nil, err
  23. }
  24. ds := NewDataset(records[0])
  25. for i := 1; i < len(records); i++ {
  26. // this is odd
  27. row := make([]interface{}, len(records[i]))
  28. for k, v := range records[i] {
  29. row[k] = v
  30. }
  31. ds.Append(row)
  32. }
  33. return ds, nil
  34. }
  35. // TSV returns a TSV representation of the Dataset as string.
  36. func (d *Dataset) TSV() (*Exportable, error) {
  37. records := d.Records()
  38. b := newBuffer()
  39. w := csv.NewWriter(b)
  40. w.Comma = '\t'
  41. w.WriteAll(records) // calls Flush internally
  42. if err := w.Error(); err != nil {
  43. return nil, err
  44. }
  45. return newExportable(b), nil
  46. }
  47. // LoadTSV loads a Dataset by its TSV representation.
  48. func LoadTSV(input []byte) (*Dataset, error) {
  49. reader := csv.NewReader(bytes.NewReader(input))
  50. reader.Comma = '\t'
  51. records, err := reader.ReadAll()
  52. if err != nil {
  53. return nil, err
  54. }
  55. ds := NewDataset(records[0])
  56. for i := 1; i < len(records); i++ {
  57. // this is odd
  58. row := make([]interface{}, len(records[i]))
  59. for k, v := range records[i] {
  60. row[k] = v
  61. }
  62. ds.Append(row)
  63. }
  64. return ds, nil
  65. }