1
3

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.

【Flask】openpyxl でExcelファイルに書き込みダウンロードさせるサンプル

Posted at

環境

・Python3
・Flask 2.1.1
・openpyxl 3.0.9

サンプル

Python

import datetime
from flask import Flask, render_template,request,send_file
from io import BytesIO
import openpyxl as excel

app = Flask(__name__)  # アプリの設定

# TOP画面
@app.route('/')
def top():
    return render_template('temp_download.html')

# ダウンロード機能
@app.route('/download')
def download():
    # 出力先ストリームの設定
    output = BytesIO()

    # テンプレートファイルを読み込み 今回は部署名と名前の入力枠を用意
    wb = excel.load_workbook('excel_template.xlsx')
    ws = wb.active
 
    # サンプルデータの書き込み 指定のセルに部署名と名前を書き込む
    ws['C2'].value = '営業部'
    ws['C3'].value = 'テスト太郎'
    
    #ワークブックをメモリ上へ出力
    wb.save(output)
    output.seek(0)
    wb.close()

    # 書き込みファイル名は時間を使用
    dt_now = datetime.datetime.now()
    name = 'test_{date}.xlsx'.format(date=dt_now.strftime('%Y%m%d%H%M%S'))

    # ブラウザへExcelファイルを設定
    return send_file(output, attachment_filename=name, as_attachment=True)

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

    # IPの指定、ポートの指定
    app.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-04-06 17.28.36.png

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?