生成CSV文件
package mainimport ("encoding/csv""log""os")var data = [][]string{{"tom", "18", "beijing"}, {"jon", "19", "shanghai"}}func main() {file, err := os.Create("1.csv")handlerError("create csv file failed", err)defer file.Close()writer := csv.NewWriter(file)defer writer.Flush()var header []string = []string{"name", "age", "address"}// 写入CSV文件头err = writer.Write(header)handlerError("write to csv file failed", err)// 方式以,逐条写入for _, value := range data {err := writer.Write(value)//err := writer.Write([]string{"tom", "18", "beijing"})handlerError("write to csv file failed", err)}// 方式二,一次性写入,本质还是调用的Write(record []string)方法err = writer.WriteAll(data)handlerError("write to csv file failed", err) }func handlerError(message string, err error) {if err != nil {log.Fatal(message, err)}}
查看生成的CSV文件
读取CSV文件
package mainimport ("encoding/csv""fmt""io""log""os")func HandlerError(msg string, err error) {if err != nil {log.Fatal(msg, err)}}func main() {f, err := os.Open("1.csv")HandlerError("open csv file failed", err)reader := csv.NewReader(f)// 一次性读取整个CSV文件result, err := reader.ReadAll()HandlerError("read all csv failed", err)fmt.Println(result)// 也可以逐行进行读取// 返回一个slicefor {record, err := reader.Read()if err == io.EOF {break}HandlerError("read csv file failed", err)fmt.Println(record)}}
输出如下: