How to export to CSV in Golang?

Alon Loeffler picture Alon Loeffler · Apr 5, 2018 · Viewed 12.9k times · Source

I have the following open-source code to generate ripple addresses and secret keys, but I want to export the output to .csv or .xlsx files. I've tried writing a function by importing the "encoding/csv" package, but I'm not very good with golang, and can't get it to work. Any suggestions?

I also want it to iterate n number of times to generate as many keys as I want.

This is the open-source code from bitbucket.org/dchapes/ripple/cmd/:

  package main

import (
    "flag"
    "fmt"
    "log"

    "bitbucket.org/dchapes/ripple/crypto/rkey"
)

func main() {
    secret := flag.String("secret", "",
        "Ripple secret, if empty gernate a random one")
    flag.Parse()

    var s *rkey.FamilySeed
    var err error
    if *secret != "" {
        s, err = rkey.NewFamilySeed(*secret)
    } else {
        s, err = rkey.GenerateSeed()
    }
    if err != nil {
        log.Fatal(err)
    }

    pubkey := s.PrivateGenerator.PublicGenerator.Generate(0)
    addr := pubkey.Address()

    if *secret == "" {
        if b, err := s.MarshalText(); err != nil {
            log.Fatal(err)
        } else {
            *secret = string(b)
        }
        fmt.Println(" secret:", *secret)
        fmt.Println("address:", addr)
    } else {
        fmt.Println(addr)
    }
}

and this is the code i tried to embed without success:

package main

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

var data = [][]string{{"Line1", "Hello Readers of"}, {"Line2", "golangcode.com"}}

func main() {
    file, err := os.Create("result.csv")
    checkError("Cannot create file", err)
    defer file.Close()

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

    for _, value := range data {
        err := writer.Write(value)
        checkError("Cannot write to file", err)
    }
}

func checkError(message string, err error) {
    if err != nil {
        log.Fatal(message, err)
    }
}

Here is an example of what I tried (combining the two)

package main

import (
"flag"
"fmt"
"log"
"os"
"encoding/csv"

"bitbucket.org/dchapes/ripple/crypto/rkey")

func main() {

for i:= 0; i < 2000; i++ {
secret := flag.String("secret", "",
    "Ripple secret, if empty generate a random one")
flag.Parse()

var s *rkey.FamilySeed
var err error
if *secret != "" {
    s, err = rkey.NewFamilySeed(*secret)
} else {
    s, err = rkey.GenerateSeed()
}
if err != nil {
    log.Fatal(err)
}

pubkey := s.PrivateGenerator.PublicGenerator.Generate(0)
addr := pubkey.Address()

if *secret == "" {
    if b, err := s.MarshalText(); err != nil {
        log.Fatal(err)
    } else {
        *secret = string(b)
    }
    fmt.Println(" secret:", *secret)
    fmt.Println("address:", addr)
} else {
    fmt.Println(addr)
}
var data(i)=[][]string{{"secret: ", *secret},{"address: ", addr}}
CSVExport(data(i))
}
}

func CSVExport(data(i) string){
file, err := os.Create("result.csv")
    checkError("Cannot create file", err)
    defer file.Close()

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

    for _, value := range data(i) {
        err := writer.Write(value)
        checkError("Cannot write to file", err)
    }
}

func checkError(message string, err error) {
if err != nil {
        log.Fatal(message, err)
    }
}

Answer

kontrollanten picture kontrollanten · Dec 18, 2018

To bulk write you can use WriteAll, see full example at https://golang.org/src/encoding/csv/example_test.go

func ExampleWriter_WriteAll() {
    records := [][]string{
        {"first_name", "last_name", "username"},
        {"Rob", "Pike", "rob"},
        {"Ken", "Thompson", "ken"},
        {"Robert", "Griesemer", "gri"},
    }

    w := csv.NewWriter(os.Stdout)
    w.WriteAll(records) // calls Flush internally

    if err := w.Error(); err != nil {
        log.Fatalln("error writing csv:", err)
    }
    // Output:
    // first_name,last_name,username
    // Rob,Pike,rob
    // Ken,Thompson,ken
    // Robert,Griesemer,gri
}