Go Program for CSV Writer

Go Program for CSV Writer

CSV means comma separated values and it is one of the most common format to import and export in spreadsheets and databases.

encoding/csv module has the functionalities to read or write the CSV format data.

This Go program is used the create the csv format data file using auto generated Student objects.

package main                                                                                                        

import (                                                                        
    "fmt"                                                                       
    "os"                                                                        
    "encoding/csv"                                                              
)                                        

func main() {                                                                   

    type Student struct {                                                       
        Id string                                                               
        Name string                                                             
        Class string                                                            
    }                      

   // creating csv file                                                     
    csvFile, err := os.Create("test-file1.csv")                                 
    if err!=nil {                                                               
        fmt.Println(err)                                                        
    }                                                                           
    defer csvFile.Close()                                                       

    // creating writer object for csv file
    csvWriter := csv.NewWriter(csvFile)                                         
    // Specify the delimiter
    csvWriter.Comma = ','                                                       

    var stu Student                                                             
    var students []Student                                                      
                                
    // Auto generates 2 Student objects     
    for i:=1;i<3;i++ {                                                          
        row :=  fmt.Sprintf("%d",i)                                             
        stu.Id = row                                                            
        stu.Name = "student"+row                                                
        stu.Class = "grade"+row                                                 
        students = append(students, stu)                                        
    }     

    // Displays the generated fields    
    fmt.Println("All Students")                                                 
    fmt.Println(students)                                                       

    // Adding all the students in CSV file using csv writer object     
    for _,stu := range students {                                               
        row := []string{stu.Id, stu.Name, stu.Class}                            
        err := csvWriter.Write(row)                                             
        if err != nil {                                                         
            fmt.Println("Error:", err)                                          
            return                                                              
        }                                                                       
    }                                                                           
    csvWriter.Flush()                                                           
    fmt.Println("CSV file is created!")                                         
} 

Output:
$ go build csv-writer.go
$ ./csv-writer
All Students
[{1 student1 grade1} {2 student2 grade2}]
CSV file is created!
$ cat test-file1.csv
1,student1,grade1
2,student2,grade2

Go Programming Write CSV Data in Console

Instead of creating csv file and providing file to CSV writer, we can also use os.Stdout to print the CSV format Students data in console.

This Go program is used to generate CSV data from Students objects.

package main         

import (               
    "fmt"                                                                       
    "os"   
    "encoding/csv"                                                              
)                                                                               
                                                                               
func main() {                                                                   
    records := [][]string{                                                      
        {"id", "name", "class"},                                                
        {"1", "student1", "VII"},                                               
        {"2", "student2", "VIII"},                                              
        {"3", "student3", "XI"},                                                
     }                                                                          

    csvWriter:= csv.NewWriter(os.Stdout)                                        
    csvWriter.WriteAll(records)                                                 
    csvWriter.Flush()                                                           
    fmt.Println("CSV format data is displayed!")                                
                                                                              
} 
Output:
$ go build csv-writer1.go
$ ./csv-writer1
id,name,class
1,student1,VII
2,student2,VIII
3,student3,XI
CSV format data is displayed!