Go Programming CSV Writer

Go Programming 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!

Java Programming Examples

GCD and Rational Number Java Program

Java Queue Program using exception

Java Stack Program using exception

Addition of three integers java program

Biggest of three integers java program

Fibonacci numbers java program

Arithmetic Operations Menu java program

Second Smallest Element In Array Java Program

Transpose Of A Matrix Java Program

Java Program to Display triangle of stars (*)

Java Programming Prints Product Tables

Java Program to Display triangle of numbers

Java Programming Gets Current Date

Java Programming Finds Character Vowel or Consonent

Java Programming HCF and LCM Computation

Java Programming Sum of Command Line Integer Arguments

Java Programming Multiplication of Command Line Integer Arguments

Java Programming Multiplication of Command Line Floating Point Numeric Arguments

Java Programming String Contains or Not

Java Programming Gets Grade Description using Switch

Java Programming CSV File Reader

Java Programming Character Frequency Count in String using for each

Java Programming Finds Min from Integer Array by Passing Array to Method

Java Programming Linear Search

Java Programming Binary Search

Java Programming Ternary Search

Java Programming Generates Range of Numbers

Java Programming Generates Range of Characters

Java Programming Computes Square Root Value

Java Programming Checks Number is Positive or Negative

Java Programming Checks Number is Odd or Even

Java Programming Computes Plot Area

Java Programming Convert Number of Days into Years

Java Programming Checks a Year is Leap Year, Century Year or Not

Java Programming Checks a Character is Digit, Letter or neither digit nor letter

Java Programming Checks a Number is Palindrome or not

Java Programming Sum of Two Matrix

Java Programming Power Computation

Java Programming Checks Number is an Armstrong Number or not

Java Programming Temperature Unit Conversions

Java Programming Generates Random Numbers in Specified Range

Java Programming Computes Sum of Digits and Product of Digits

Java Programming Computes Reverse Number

Java Programming Computes Factorial Value

Java Programming Checks Prime Number or not

Java Programming Computes Harmonic Series

Java Programming Generates Floyd's Triangle

Java Programming Reverses String

Java Programming Checks Palindrome String or not

Java Programming Opens Notepad

Java Programming Searches String using RegEx Pattern

Java Programming Searches Word in String

Java Programming Gets System Environment Variables

Java Programming Gets IP Address of Server Name

Java Programming Arrays Sort and Reverse using sort method

Java Programming Bubble Sorting

Java Programming Selection Sorting

Java Programming Insertion Sorting

Java Programming Merge Sorting

Java Programming Quick Sorting

Java Programming Counting Sort

Java Programming Radix Sorting

Java Programming Sorting Array of Strings

Java Programming String Characters Sorting

Java Programming Sum of First N Numbers

Java Programming Product of First N Numbers

Privacy Policy  |  Copyright@2017 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Free online programming tutorials

Email Facebook Google LinkedIn Twitter
^