LoginSignup
0
0

More than 3 years have passed since last update.

Pandas DataFrame を CSV ファイルとしてダウンロードさせる

Last updated at Posted at 2020-03-05

Web サーバを Python で作っていて、Pandas DataFrame を CSV ファイルとしてダウンロードさせたいときのメモ。

body = df.to_csv(index=False).encode('utf_8_sig')
headers = {
    'Content-Type': 'text/csv',
    'Content-Disposition': 'attachment; filename="data.csv"',
}
return web.Response(body=body, headers=headers)

これは aiohttp Server の例だが、他のフレームワークでも同様だと思う。

  • pandas.DataFrame.to_csv は出力先を指定しなければそのまま CSV 文字列を返してくれる
  • CSV ファイルが Excel で開かれることが想定される場合は utf_8_sig (BOM 付き UTF-8) でエンコードしておくと文字化けしなくて良い
  • Content-Disposition ヘッダを付加することでダウンロード時のファイル名を指定することができる
    • 日本語ファイル名を使う時はエンコードが必要

このあたりがポイント。

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