LoginSignup
1
2

More than 5 years have passed since last update.

Django で xlsx を更新してダウンロード

Last updated at Posted at 2019-01-20

こちらの記事と同様のことを Arch Linux で行ってみました。
Python + Django でExcelをダウンロードする

テンプレートは、次の記事で作成した cities.xlsx を /var/tmp/xlsx
に置きました。 シート名は Cities です。

1) プロジェクトとアプリの作成

プロジェクト proj01
アプリ excelapp1

django-admin startproject proj01
cd proj01/
python manage.py startapp excelapp1

2) excelapp1/urls.py の作成

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

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

3) excelapp1/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('/var/tmp/xlsx/cities.xlsx')

    sheet = wb['Cities']
    sheet['C4'] = '99999'
    sheet['D4'] = '2019-1-20'

# 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

4) proj01/settings.py の編集

proj01/settings.py
省略
INSTALLED_APPS = [
    'excelapp1',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]
省略

5) proj01/urls.py の編集

proj01/urls.py
from django.contrib import admin
from django.urls import path
from django.urls import include

urlpatterns = [
    path('excelapp1/', include('excelapp1.urls')),
    path('admin/', admin.site.urls),
]

6) 開発サーバーの起動

python manage.py runserver

7) ブラウザーで
http://127.0.0.1:8000/excelapp1/
にアクセス

テンプレートの xlsx
xlsx_jan2001.png

更新してダウンロードした xlsx
xlsx_jan2002.png

コードは、こちらにあります。
ekzemplaro/django_xlsx_update

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