Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Tuesday, April 11, 2023

Write Data to CSV File using Golang

 CSV (Comma Separated Value) is the most used file format to store and share the data. It is widely used in web applications to export and import dynamic data.

Step1: Create Golang File To Write Data to CSV File

We will create main.go file and import necessary packages. We will import encoding/csv package to write data to CSV file.

package main

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

Step2: Create Data Array to Write to CSV File

We will create a multi dimensional array with employee data to write to CSV file . We will iterate this array and save it to a employee.csv file.

empData := [][]string{
		{"Name", "City", "Skills"},
		{"Smith", "Newyork", "Java"},
		{"William", "Paris", "Golang"},
		{"Rose", "London", "PHP"},
	}

Step3: Create CSV File

We will create the CSV file using os package from Go. After opening the CSV file, we will handle functionality to write to CSV file and close the file.

csvFile, err := os.Create("employee.csv")

if err != nil {
	log.Fatalf("failed creating file: %s", err)
}
csvFile.Close()

Step4: Write Data to CSV File

We will use csv.NewWriter() method to write to CSV file. We will loop through employee data array and write rows to CSV file.

csvwriter := csv.NewWriter(csvFile)
 
for _, empRow := range empData {
	_ = csvwriter.Write(empRow)
}

csvwriter.Flush()

Step4: Complete Code to write data to the CSV File in Golang

Here is the complete code to write data to the CSV file using Golang.

package main

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

empData := [][]string{
	{"Name", "City", "Skills"},
	{"Smith", "Newyork", "Java"},
	{"William", "Paris", "Golang"},
	{"Rose", "London", "PHP"},
}

csvFile, err := os.Create("employee.csv")

if err != nil {
	log.Fatalf("failed creating file: %s", err)
}

csvwriter := csv.NewWriter(csvFile)
 
for _, empRow := range empData {
	_ = csvwriter.Write(empRow)
}
csvwriter.Flush()
csvFile.Close()

The result will be:

 

Name, City, Skills
Smith, Newyork, Java
William, Paris, Golang
Rose, London, PHP

Conclusion

Hopefully this tutorial helped you to write data to the CSV file in Golang. If you find this tutorial helpful then please let us know in the comments section below.

 

No comments:

Post a Comment