📚Cheatsheets

Cheatsheet collection for go, rust and javascript.

How to write csv in Golang?

Just use standard package from golang like this.

package main

import (
	"encoding/csv"
	"os"
)

func main() {

	header := []string{"name", "age"}
	body := [][]string{{"ahmad", "12"}, {"rosid", "24"}}

	if err := writeToCsv("data.csv", header, body); err != nil {
		panic(err)
	}
}

func writeToCsv(filename string, header []string, body [][]string) error {
	data := [][]string{header}
	data = append(data, body...)

	f, err := os.Create(filename)
	if err != nil {
		return err
	}

	writer := csv.NewWriter(f)
	defer writer.Flush()

	for _, row := range data {
		if err := writer.Write(row); err != nil {
			return err
		}
	}
	return nil
}