LoginSignup
1
1

More than 3 years have passed since last update.

ScalaのPlayで SeqデータからShift-JISのCSVを出力する

Last updated at Posted at 2018-10-16

ScalaでPlayFramworkのレスポンスで Shift_JISのCSVを出力する

↑↑↑↑↑↑↑ 編集リクエストの内容

CSVでダウンロードさせたいみたいな案件がある時に有効。

条件

1, CSVライブラリにはPureCSVを使う
https://github.com/melrief/PureCSV
2, Shift-JISに変換するのはPlayの機能で補う

実装

  • purecsvのREADMEに書かれてるとおりに build.sbt を記述
resolvers += Resolver.sonatypeRepo("releases")
libraryDependencies += "com.github.melrief" %% "purecsv" % "0.1.1"
  • Controllerを実装
import play.api.mvc.Codec
import purecsv.safe._

case class CSV(id: String, name: String)
val header = CSV("ID", "氏名")
val csv = header +: Seq(CSV("1", "ヤマダ"), CSV("2", "スズキ"))

implicit val myCustomCharset = Codec.javaSupported("Shift_JIS")
Ok(csv.toCSV()).as("text/csv; charset=shift_jis")

最後の2行で、Shift-JIS指定ができる。Content-Typeも書き換わってくれる。
指定したroutes にアクセスすると、Shift-JISのCSVが取得できる

1
1
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
1
1