Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

Go GoCSVでShift_JISでCRLFなCSVを作る

More than 1 year has passed since last update.

ソース

package main

import (
    "encoding/csv"
    "fmt"
    "io"
    "os"
    "time"

    "golang.org/x/text/encoding/japanese"
    "golang.org/x/text/transform"

    "github.com/gocarina/gocsv"
)

const layout = "20060102150405"

type User struct {
    Name string `csv:"名前"`
    Mail string `csv:"メール"`
    Age  string `csv:"age"`
}

func main() {
    var users []*User
    users = append(users, &User{
        Name: "ほげ",
        Mail: "hoge@example.com",
        Age:  "21",
    })

    gocsv.SetCSVWriter(func(out io.Writer) *gocsv.SafeCSVWriter {
        writer := csv.NewWriter(transform.NewWriter(out, japanese.ShiftJIS.NewEncoder()))
        writer.UseCRLF = true
        return gocsv.NewSafeCSVWriter(writer)
    })

    now := time.Now()
    file, err := os.OpenFile(now.Format(layout)+".csv", os.O_CREATE|os.O_WRONLY, os.ModePerm)
    if err != nil {
        fmt.Println(err)
    }
    defer file.Close()

    gocsv.MarshalFile(&users, file)
}

参考

参考2

hiro9
ガンバルンバ
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away