關於這裏只把示例部分的url.py view.py html模板部分html
url.pypython
from django.conf.urls import include, url from django.contrib import admin from mysites.views import index, upload_file, report_down_load urlpatterns = [ # Examples: # url(r'^$', 'untitled1.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^index/$', index), url(r'^upload_file/$', upload_file), url(r'^report_down_load/$', report_down_load), ]
view.pydjango
from django.http import HttpResponse from django.shortcuts import render, render_to_response import os import xlrd # Create your views here. from django.template import RequestContext from django.views.decorators.csrf import csrf_exempt def index(request): return render_to_response("index.html", '', context_instance=RequestContext(request)) @csrf_exempt def upload_file(request): if request.method == 'POST': myFile = request.FILES.get('myfile', None) if not myFile: return HttpResponse('no file for upload') excelFile = open(os.path.join('/Users/eruake/Desktop/code/hkwork/untitled1/', myFile.name), 'wb+') for chunk in myFile.chunks(): excelFile.write(chunk) excelFile.close() # excel = xlrd.open_workbook('/Users/eruake/Desktop/code/hkwork/untitled1/'+myFile.name) sheet = excel.sheet_by_index(0) # sheet = excel.sheet_by_name('mywork') nrows = sheet.nrows for i in range(nrows): # get value you can save to database v = sheet.cell(0, 0).value return HttpResponse('upload over!') import xlwt import django.utils.timezone as timezone @csrf_exempt def report_down_load(request): wb = xlwt.Workbook() sheet = wb.add_sheet('report') filename = timezone.now().strftime("%Y%m%d %H%M%S") + '.xls' # # set data # and set xls file style 這裏要說明一點的時,咱們能夠設置excel模板的樣式,能夠經過xlrd先讀取,再使用xlutils.copy # 來實現寫,可是因爲xlutils是不能讀取複製樣式,如背景顏色 字體樣式等 因此我建議直接使用xlwt來控制樣式 response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=' + filename wb.save(response) return response
template 裏的index.htmlapp
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form enctype="multipart/form-data" action="/upload_file/" method="post"> <input type="file" name="myfile" /> <br/> <input type="submit" value="upload"/> </form> <p>------------------------</p> <form enctype="multipart/form-data" action="/report_down_load/" method="post"> <input type="submit" value="download"/> </form> </body> </html>