导出csv文件
func WriteCsv() {//创建文件f, err := os.Create("test.csv")if err != nil {panic(err)}defer f.Close()// 写入UTF-8 BOMf.WriteString("\xEF\xBB\xBF")//创建一个新的写入文件流w := csv.NewWriter(f)data := [][]string{{"1", "刘备", "23"},{"2", "张飞", "23"},{"3", "关羽", "23"},{"4", "赵云", "23"},{"5", "黄忠", "23"},{"6", "马超", "23"},}//写入数据w.WriteAll(data)w.Flush()
}
读取csv
func ReadCsv() {//准备读取文件fileName := "test.csv"fs, err := os.Open(fileName)if err != nil {log.Fatalf("can not open the file, err is %+v", err)}defer fs.Close()r := csv.NewReader(fs)//针对大文件,一行一行的读取文件for {row, err := r.Read()if err != nil && err != io.EOF {log.Fatalf("can not read, err is %+v", err)}if err == io.EOF {break}fmt.Println(row)}fmt.Println("\n---------------------------\n")// 针对小文件,也可以一次性读取所有的文件。注意,r要重新赋值,因为readall是读取剩下的fs1, _ := os.Open(fileName)r1 := csv.NewReader(fs1)content, err := r1.ReadAll()if err != nil {log.Fatalf("can not readall, err is %+v", err)}for _, row := range content {fmt.Println(row)}
}