csv

package module
v1.0.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 28, 2023 License: BSD-3-Clause Imports: 12 Imported by: 0

README

CSV For Golang

CI status

csv-go is csv/tsv/psv file helper, current supported csv, tsv, psv format.

Use it to help you process data quickly.

Install

go get github.com/hiscaler/csv-go

Notices

Row and Column start index from 1, not 0

Usage

Open file
csv := NewCSV()
err := csv.Open("./testdata/test.csv")
if err != nil {
    panic(err)
}
defer csv.Close()
Reset

You can use it reset csv file, and re-read the file.

csv.Reset()

after reset, file reader config will remain the same.

Reads all rows
for {
    row, isEOF, err := csv.Row()
    if isEOF {
        break
    }
    if err != nil {
        log.Fatal(err)
    }
    // Read first column data with current row, and add "A" prefix return value
    column := row.Column(1).
        TrimSpace().
        Do(func(s string) string {
            return s + "A"
        })    

    column = row.Column(1).
        TrimSpace().
        Do(func(s string) string {
            // change return value
            v := ""
            switch s {
            case "one":
                v = "1"
            case "two":
                v = "2"
            case "three":
                v = "3"
            default:
                v = ""
            }
            return v
        })
    if row.Number != 1 {
        i, _ := column.ToInt()
        fmt.Println(i)
    }
}
Reads a row
row, isEOF, err := csv.Row()
Change row data

If you want to fix column value in current row, you can do it:

row.Map(func (s string) string {
    return "PREFIX_" + s
}, 1)

The above code change first column value, will return "PREFIX_" and original column value concatenated string.

If you want change all columns value, don't pass columnIndex parameter value. Then all columns value will add "PREFIX_" prefix string.

Change a column value
column := row.Column(1).TrimSpace()

Will remove the spaces on both sides

or you can use Do() method perform custom processing, example:

column := row.Column(1).Do(func(s string) string {
    if s == "a" {
        return "Number One"
    } else if s == "" {
        return "SOS"
    }
    return s
})
Reads a column in the current row
// Read first column in current row
column := row.Column(1)
column.TrimSpace() // Clear spaces
column.Do(func(s string) string {
	// process value
	return s
}) // Use Do method process value
column.String() // get string value

// if you want to get correct value, you will check err and continue
v, err := column.ToInt() // get int value
v, err := column.ToInt("100") // get int value, and return 100 if value is empty
v, err := column.ToFloat64() // get float value
v, err := column.ToFloat64("100.00") // get float value, and return 100.00 if value is empty
v, err := column.ToBool() // get boolean value
v, err := column.ToBool("false") // get boolean value, and return false if value is empty
v, err := column.ToTime("2006-01-02", time.Local) // get time value
v, err := column.ToTime("2006-01-02", time.Local, "2022-01-01") // get time value, and return 2022-01-01 if value is empty

Valid column value conversion methods

  • String()
  • ToBytes()
  • ToInt()
  • ToInt8()
  • ToInt16()
  • ToInt32()
  • ToInt64()
  • ToFloat32()
  • ToFloat64()
  • ToBool()
  • ToTime()
Save file

SaveAs() use to save a file.

This method help you create saved directory if not exists, and check you file extension save to csv/tsv/psv format. if save have any error will return it.

records := make([][]string, 0)
for {
    row, isEOF, err := csvInstance.Row()
    if isEOF {
        break
    }
    if err != nil {
        log.Fatal(err)
    }
    // Do what you want to do 
    row.Map(func(s string) string {
        if row.Number != 1 {
            // Ignore header
            s = `1, "change"` + s
        }
        return s
    })
    records = append(records, row.Columns)
}
err := csvInstance.SaveAs("./a.csv", records)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CSV

type CSV struct {
	Reader *csv.Reader // File Reader
	// contains filtered or unexported fields
}

func NewCSV

func NewCSV() *CSV

func (*CSV) Close

func (c *CSV) Close() error

Close closes open file

func (*CSV) FindAll added in v1.0.7

func (c *CSV) FindAll(s string, fuzzy bool) (indexes []Value, err error)

FindAll Find all matched value row/column indexes

func (*CSV) FindFirst added in v1.0.7

func (c *CSV) FindFirst(s string, fuzzy bool) (value Value, err error)

FindFirst Find first matched value row/column index

func (*CSV) FindLast added in v1.0.7

func (c *CSV) FindLast(value string, fuzzy bool) (index Value, err error)

FindLast Find last matched value row/column index

func (*CSV) Open

func (c *CSV) Open(filename string) error

Open opens a csv file

func (*CSV) Reset added in v1.0.4

func (c *CSV) Reset() error

Reset resets to the file header, and set new Reader, used to re-read the file

func (*CSV) Row

func (c *CSV) Row() (r Row, isEOF bool, err error)

Row read one row from opened file

func (*CSV) SaveAs

func (c *CSV) SaveAs(filename string, records [][]string) error

SaveAs save as file

type Column

type Column struct {
	OriginalValue string // Original value
	NewValue      string // New value process after
	// contains filtered or unexported fields
}

Column line of data in file

func (*Column) Do

func (c *Column) Do(f func(s string) string) *Column

func (*Column) IsBlank added in v1.0.5

func (c *Column) IsBlank() bool

func (*Column) IsEmpty

func (c *Column) IsEmpty() bool

func (*Column) IsNull added in v1.0.5

func (c *Column) IsNull() bool

func (*Column) String

func (c *Column) String() string

func (*Column) ToBool

func (c *Column) ToBool(defaultValue ...string) (bool, error)

func (*Column) ToBytes added in v1.0.4

func (c *Column) ToBytes(defaultValue ...string) []byte

func (*Column) ToFloat32

func (c *Column) ToFloat32(defaultValue ...string) (float32, error)

func (*Column) ToFloat64

func (c *Column) ToFloat64(defaultValue ...string) (float64, error)

func (*Column) ToInt

func (c *Column) ToInt(defaultValue ...string) (int, error)

func (*Column) ToInt16

func (c *Column) ToInt16(defaultValue ...string) (int16, error)

func (*Column) ToInt32

func (c *Column) ToInt32(defaultValue ...string) (int32, error)

func (*Column) ToInt64

func (c *Column) ToInt64(defaultValue ...string) (int64, error)

func (*Column) ToInt8

func (c *Column) ToInt8(defaultValue ...string) (int8, error)

func (*Column) ToTime

func (c *Column) ToTime(layout string, loc *time.Location, defaultValue ...string) (time.Time, error)

func (*Column) TrimSpace

func (c *Column) TrimSpace() *Column

TrimSpace trim both space with original value

type Row

type Row struct {
	Number  int
	Columns []string
}

func (*Row) Column

func (r *Row) Column(index int) *Column

Column reads column value in current row, column index start 1

func (*Row) Every

func (r *Row) Every(f func(r *Row) bool) bool

Every check condition is passed for all columns value in current row

func (*Row) IsEmpty

func (r *Row) IsEmpty() bool

func (*Row) Map

func (r *Row) Map(f func(s string) string, columnIndex ...int) *Row

Map process all columns value in current row

func (*Row) Write

func (r *Row) Write(column *Column) *Row

Write writes column value in current row

type Rows

type Rows []Row

type Value added in v1.0.9

type Value struct {
	Row  int
	Col  int
	Data []string
}

func (*Value) Column added in v1.0.9

func (v *Value) Column(i int) *Column

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL