dongyuedaochen8415
2018-04-05 05:07
浏览 155
已采纳

如何在Golang中导出为CSV?

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)
    }
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doulan3436 2018-04-06 19:54
    已采纳

    Hi @alon: here is a start of some code for you to look at. I would say you would get a lot out of some basic go tutorials. I am not familiar with what you are actually trying to do with this data, as well, but this code generates a csv file with random secrets and some related addresses.

    It would be helpful for people helping you out to gofmt your source code, that would make it much easier to follow along.

    package main
    
    import (
        "encoding/csv"
        "fmt"
        "log"
        "os"
    
        "bitbucket.org/dchapes/ripple/crypto/rkey"
    )
    
    func main() {
        var secret string
        // instead of defining data over and over, let's define it once then accumulate things into it.
        data := [][]string{}
        data = append(data, []string{"secret", "address"})
        for i := 0; i < 2000; i++ {
            var s *rkey.FamilySeed
            s, err := rkey.GenerateSeed()
            if err != nil {
                log.Fatal(err)
            }
    
            pubkey := s.PrivateGenerator.PublicGenerator.Generate(0)
            addr := pubkey.Address()
    
            if b, err := s.MarshalText(); err != nil {
                log.Fatal(err)
            } else {
                secret = string(b)
            }
            fmt.Printf("Secret:%s\tAddress:%s
    ", secret, addr)
            data = append(data, []string{secret, addr})
    
        }
        // Instead of writing 2000 csv files over each other, let's write one with
        // 2000 lines instead.
        if err := csvExport(data); err != nil {
            log.Fatal(err)
        }
    }
    
    // Changed to csvExport, as it doesn't make much sense to export things from
    // package main
    func csvExport(data [][]string) error {
        file, err := os.Create("result.csv")
        if err != nil {
            return err
        }
        defer file.Close()
    
        writer := csv.NewWriter(file)
        defer writer.Flush()
    
        for _, value := range data {
            if err := writer.Write(value); err != nil {
                return err // let's return errors if necessary, rather than having a one-size-fits-all error handler
            }
        }
        return nil
    }
    
    点赞 打赏 评论
  • donglei2022 2018-12-18 20:20

    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
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题