Skip to main content

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.

In our previous tutorial you have learned how to read CSV file in Golang. In this tutorial you will learn how to write data to the CSV file using Golang. The Go has encoding/csv package which has NewWriter() method. The NewWriter() method returns a Writer object which is used for writing CSV data. The csv.Writer obejct writes csv records which are terminated by a newline and uses a comma as the field delimiter.

We will cover this tutorial step by step to create CSV file and write to records to CSV file using Golang.

Also, read:

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.

You may also like: