1
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 1 year has passed since last update.

【bottle】Pandasで生成したExcelをダウンロードさせるサンプル

Last updated at Posted at 2022-03-07

環境

・Python3
・bottle 0.12.19
・pandas 1.4.1

サンプル

Python

import datetime
from bottle import run, template, route,response
from io import BytesIO
from pandas import ExcelWriter
import pandas as pd

# TOP画面
@route('/')
def hello():
    return template('temp_download')

# ダウンロード機能
@route('/download')
def download():
    output = BytesIO()
    writer = ExcelWriter(output, engine='xlsxwriter')

    # Excel書き込みデータの準備
    # 書き込みデータはサンプル
    data_list = [["One",1],["Two",2],["Three",3]] 
    df = pd.DataFrame(data_list)
    
    # Excel出力
    df.to_excel(writer, sheet_name='Sheet1')
    writer.save()

    # 書き込みファイル名は時間を使用
    dt_now = datetime.datetime.now()
    name = 'test_{date}.xlsx'.format(date=dt_now.strftime('%Y%m%d%H%M%S'))
    
    # ダウンロード処理
    response.contet_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    response.add_header('Content-Disposition', 'attachment; filename="{name}"'.format(name=name))
    return output.getvalue()


# メイン起動
if __name__ == "__main__":

    # IPの指定、ポートの指定
    run(host='localhost', port=8080)

HTML

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>Excelダウンロードページ</title>
</head>
<body>
    <button type=“button” onclick="location.href='/download'">ダウンロード</button>
    
</body>
</html>

出力結果

スクリーンショット 2022-02-28 15.45.32.png

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?