0
1

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 3 years have passed since last update.

[Ktor]CSVファイルをDLさせる

Last updated at Posted at 2021-09-24

やりたいこと

こんな感じのデータがあったとして

data class Sale (
    val date: String = "",
    var price: Int = 0
)

val saleList: MutableList<Sale>> = mutableListOf(
  Sale("2021-01-10", 500),
  Sale("2021-03-20", 500),
  Sale("2021-02-15", 300)
)

以下のようなCSVにしてDLさせます

"日付","売上"
"2021-01-10", "500"
"2021-03-20", "500"
"2021-02-15", "300"

やり方

data classの方に、ヘッダー名の定義を設定します。

data class Sale (
    @CsvBindByName(column = "日付", required = true)
    val date: String = "",

    @CsvBindByName(column = "売上金額", required = true)
    var price: Int = 0
)

CSVにして返却します。やり方は色々あると思いますが、自分は一時ファイルに書き出して返却するようにしました。

// 一時CSVに内容を書き出す
val writer: Writer = FileWriter("tmp.csv")
val beanWriter = StatefulBeanToCsvBuilder<Sale>(writer).build()
saleList.map {
    beanWriter.write(it)
}
writer.close()

val file = File("tmp.csv")

// DL可能にする
call.response.header(HttpHeaders.ContentDisposition, ContentDisposition.Attachment.withParameter(ContentDisposition.Parameters.FileName, URLEncoder.encode("売上データ.csv", "UTF-8")).toString())

// ファイルを返却する
call.respondFile(file)

公式ドキュメントのやり方流用しているので、詳しくはこちら
https://jp.ktor.work/servers/calls/responses.html#content-negotiation

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?