Skip to content

Commit

Permalink
加入SaveCsvCfg
Browse files Browse the repository at this point in the history
  • Loading branch information
sersoong committed Dec 16, 2019
1 parent a1578c5 commit f9aabe6
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 1 deletion.
45 changes: 45 additions & 0 deletions csv.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/csv"
"log"
"os"
"reflect"
"strconv"
)

Expand Down Expand Up @@ -116,3 +117,47 @@ func LoadCsvCfg(filename string, row int) *CsvTable {
}
return result
}

//SaveCsvCfg 导出CSV文件
func SaveCsvCfg(table []map[string]interface{}, filename string) {
// 创建csv文件
file, err := os.Create(filename)
if err != nil {
log.Fatalln(err.Error())
}
defer file.Close()

// 创建csv writer
cw := csv.NewWriter(file)

var wKey []string

// 循环遍历传入的数据数组
for index, item := range table {
var wData []string
for key, dataitem := range item {
if index == 0 {
wKey = append(wKey, key)
}

switch reflect.TypeOf(dataitem).String() {
case "bool":
boolData := strconv.FormatBool(dataitem.(bool))
wData = append(wData, boolData)
case "int":
intData := strconv.Itoa(dataitem.(int))
wData = append(wData, intData)
case "float64":
floatData := strconv.FormatFloat(dataitem.(float64), 'f', -1, 64)
wData = append(wData, floatData)
default:
wData = append(wData, dataitem.(string))
}
}
if index == 0 {
cw.Write(wKey)
}
cw.Write(wData)
}
cw.Flush()
}
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/sersoong/go-csv

go 1.13
16 changes: 15 additions & 1 deletion test/main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"encoding/json"
"fmt"

csvmgr "github.com/sersoong/go-csv"
Expand All @@ -14,11 +15,24 @@ type TestTable struct {
Text string
}

//RespData RespData
type RespData struct {
Data []map[string]interface{} `json:"data"`
}

var jsondata = `{"data":[{"id":0,"name":"张三","value":"aaaaa"},{"id":1,"name":"李四","value":"bbbbb"}]}`
var gTestTable map[int]*TestTable

func main() {
LoadTestTable()
fmt.Print(gTestTable[1])

var ret RespData
json.Unmarshal([]byte(jsondata), &ret)

csvmgr.SaveCsvCfg(ret.Data, "./out.csv")
for _, item := range gTestTable {
fmt.Println(item)
}
}

//LoadTestTable 载入测试数据表
Expand Down
3 changes: 3 additions & 0 deletions test/out.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
id,name,value
0,张三,aaaaa
1,李四,bbbbb

0 comments on commit f9aabe6

Please sign in to comment.