20
23

More than 5 years have passed since last update.

Python + Django でExcelをダウンロードする

Posted at

Python + Django でExcelをダウンロードしてみます。「openpyxl」というパッケージを使います。

「openpyxl」の使い方は、Python openpyxlでExcelを操作の投稿を参照するなどするとよいと思います。

ここでは、Djnagoを使ってExcelをダウンロードする方法を投稿します。

1.環境

カテゴリ バージョンなど
os windows 10 home 64bit
python 3.6.5
django 2.1.4
project myproject
openpyxl 2.5.12

2.パッケージをインストール

以下のコマンドを実行します。

command.prompt
pip install openpyxl

3.アプリケーションの作成

「python manage.py startapp excelapp1」で以下のファイルができます。

excelapp1
│  admin.py
│  apps.py
│  models.py
│  tests.py
│  urls.py
│  views.py

""4.仕様

テンプレートファイル
フォルダ名:「C:\data\python\exceltemplates」
ファイル名;sample.xlsx
内容:
image.png

このファイルの2行目を編集してクライアントにダウンロードするようにします。

5.urls.py

excelapp1/urls.py
from django.urls import path
from . import views

app_name = 'excelapp1'
urlpatterns = [
    path('', views.index, name='index'),   # 一覧
]

6.views.py

excelapp1/views.py
from django.shortcuts import render
import os
import openpyxl
import pprint
from django.http import HttpResponse

def index(request):
    """
      Excel output from template
    """
    # Excelのテンプレートファイルの読み込み
    wb = openpyxl.load_workbook('C:/data/python/exceltemplates/sample.xlsx')

    sheet = wb['sheet1']
    sheet['C2'] = 'XXX'
    sheet['E2'] = 'new'

# Excelを返すためにcontent_typeに「application/vnd.ms-excel」をセットします。

    response = HttpResponse(content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename=%s' % 'report.xlsx'

    # データの書き込みを行なったExcelファイルを保存する
    wb.save(response)

    # 生成したHttpResponseをreturnする
    return response

7.プロジェクトにアプリを追加

myprojectのsettings.py,urls.pyをそれぞれ編集します。

myproject\settings.py
INSTALLED_APPS = [
#・・・
   'excelapp1', #追加
]
myproject\urls.py
urlpatterns = [
#・・・
    path('excelapp1/', include('excelapp1.urls')),   # ←ここを追加    
    path('admin/', admin.site.urls),
]

8.確認

URLにアクセスする
http://localhost:8000/excelapp1

image.png

Excelも無事ダウンロードできました。

20
23
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
20
23