5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Go GoCSVでShift_JISでCRLFなCSVを作る

Posted at

ソース

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

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?