如何在Golang中导出到CSV?

时间:2018-04-05 05:07:38

标签: go export-to-excel export-to-csv ripple cryptocurrency

我有以下开源代码来生成纹波地址和密钥,但我想将输出导出到.csv或.xlsx文件。我已经尝试通过导入“encoding / csv”包来编写函数,但是我对golang不是很好,并且无法让它工作。有什么建议吗?

我还希望它迭代n次以生成任意数量的键。

这是来自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)
    }
}

这是我试图嵌入但没有成功的代码:

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)
    }
}

以下是我尝试过的一个例子(将两者结合起来)

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 个答案:

答案 0 :(得分:3)

要批量写入,您可以使用1,请参见https://golang.org/src/encoding/csv/example_test.go的完整示例

WriteAll

答案 1 :(得分:1)

您好@alon:这是一些代码的开头供您查看。我会说你会从一些基本的教程中获得很多。我不熟悉您实际尝试对此数据执行的操作,但此代码生成带有随机密钥和一些相关地址的csv文件。

帮助您了解gofmt源代码的人会很有帮助,这会让您更容易理解。

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\n", 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
}