golang如何匯出csv格式的檔案
阿新 • • 發佈:2018-11-10
import(
"fmt"
"github.com/xormplus/xorm"
"golang.org/x/text/transform"
"golang.org/x/text/encoding/simplifiedchinese"
"io/ioutil"
"github.com/gin-gonic/gin"
"bytes"
"encoding/csv"
"strings"
_ "github.com/lib/pq"
"strconv"
)
...
type User struct{
Name string
Provice string
City string
Address string
TDate string
Phone string
Status int
}
func GetData(c *gin.Context) {
fileName := "test.csv"
//users, err := GetUserByDate("2018/4/3", "2018/4/3")
users = make([]User,0,10)
users = append(users,User{"ft", "jiangxi", "nanchang", "xx", time.Now(), "110", 1})
users = append (users,User{"ft2", "jiangxi", "nanchang", "xx", time.Now(), "111", 1})
users = append(users,User{"ft3", "jiangxi", "nanchang", "xx", time.Now(), "111", 1})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(users)
usersStrArray :=structs2StringArr(users)
categoryHeader := []string {"姓名","省份","城市","詳細地址","填寫日期","聯絡方式","是否聯絡"}
b := &bytes.Buffer{}
wr := csv.NewWriter(b)
wr.Write(categoryHeader) //按行shu
for i := 0; i < len(usersStrArray); i++ {
wr.Write(usersStrArray[i])
}
wr.Flush()
c.Writer.Header().Set("Content-Type", "text/csv")
c.Writer.Header().Set("Content-Disposition", fmt.Sprintf("attachment;filename=%s", fileName))
//tet, _ := UTF82GBK(b.Bytes())
tet:=b.String()
c.String(200, tet)
}
func structs2StringArr(users []User) [][]string{
var userArr =make([][]string,0)
var user = User{}
for i:=0;i<len(users);i++{
user = users[i]
userArr = append(userArr,[]string{user.Name,user.Province,user.City,user.Address,user.Tdate,user.Phone,strconv.Itoa(user.Status)})
}
return userArr
}