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

如何在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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于IMageEnView 图标定位问题
  • ¥20 求解答(matlab)
  • ¥30 ffmpeg库使用过程中遇到的问题
  • ¥15 pyqt5 中python如何通过Qtwebchannel主动发消息给web前端
  • ¥15 关于HTML中title获取xml内容的问题
  • ¥15 fanuc机器人PRIO083数字信号未复原错误,如何解决?
  • ¥20 如何为现有电路板增加远程控制功能
  • ¥15 UE5打包失败,求解决
  • ¥15 请问STM32G431的CANOPEN协议函数怎么写
  • ¥15 graphpad prism 三因素重复测定报错