• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

如何使用Django导出Excel代码问题

python 搞代码 4年前 (2022-01-09) 31次浏览 已收录 0个评论

本篇文章主要介绍了Django 导出 Excel 代码的实例详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

这篇技术贴讲怎样在Django的框架下导出Excel, 最开始打算用ajax post data 过去,但是发现不行,所以改用了get的方式。如果只有一个id(pk)那用get的方式很简单就可以访问对应的view section,但是如果是多个ids,我用的是session,大家还有其他好的例子吗?希望一起讨论。

Python3.5 Django 1.10, sqlite3, windows 10

1. virtualenv export_excel <— create a virtualenv for django

2. cd export_excel <— Go into the export_excel folder

3. Script\active <— activate env environment.

once activate the environment, in the windows would be liked as above.

4. pip install django.

5. pip install django-bootstrap3. <– bootstrap3 for django.

6. pip install xlsxwriter. <– this uses for excel export.(用xlsxwriter 这个Python 库)

1. urls.py

"""export_excel URL Configuration   The `urlpatterns` list routes URLs to views. For more information please see:   https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views   1. Add an import: from my_app import views   2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views   1. Add an import: from other_app.views import Home   2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf   1. Import the include() function: from django.conf.urls import url, include   2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url from django.contrib import admin from django.views.generic import ListView   from .models import ExcelDemoData from . import views   urlpatterns = [  <i style="color:transparent">本文来源gaodai$ma#com搞$代*码6网</i> url(r'^admin/', admin.site.urls),   url(r'^$', ListView.as_view(queryset = ExcelDemoData.objects.all().defer('id', 'part_number').order_by('id')[:100], template_name="part_num_list.html"), name = 'home'),   url(r'^demo/exportall/$', views.export_all_to_excel, name = 'export_all_to_excel'), ]

2. views.py

from django.http import JsonResponse, Http404 from django.shortcuts import render, get_object_or_404, render_to_response  from django.http import HttpResponseRedirect from django.contrib import messages from django.core.urlresolvers import reverse from django.http import HttpResponse  from .models import ExcelDemoData from .forms import ExcelDemoForm from .excel_utils import WriteToExcel  from . import attrs_override as attr       def export_sig_to_excel(request, pk):    if request.method == 'GET':     demo_list = []     try:       demo_row = ExcelDemoData.objects.get(pk = pk)     except ExcelDemoData.DoesNotExist:       messages.add_message(request, messages.ERROR, 'the Part Number: [%s] does not exist in database.' % str(pk))     else:         demo_list.append(demo_row)             response = HttpResponse(content_type='application/ms-excel')     response['Content-Disposition'] = 'attachment; filename=ExcelDemoData_%s.xlsx' % demo_row.demo_row_part_number      xlsx_data = WriteToExcel(demo_list)     response.write(xlsx_data)     return response                   def export_all_to_excel(request):   if request.method == 'GET':     if 'store_modi_id' in request.session:        messages.add_message(request, messages.ERROR, 'The Part Number have been lost, please re-search them.')        return HttpResponseRedirect(reverse('home'))            demo_list = []     pn_id_list = request.session['searched_sb_list'] #<--- the session will be created when a list page was created.     for id in pn_id_list:       try:         demo_row = ExcelDemoData.objects.get(pk = id)       except SmartBuy.DoesNotExist:         messages.add_message(request, messages.ERROR, 'the Part Number does not exist in database.' )       else:           demo_list.append(demo_row)             response = HttpResponse(content_type='application/ms-excel')     response['Content-Disposition'] = 'attachment; filename=ExcelDemoData_%s.xlsx' % attr.get_current_timestamp()      xlsx_data = WriteToExcel(demo_list)     response.write(xlsx_data)     return response

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:如何使用Django导出Excel代码问题

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址