Django 2 1 7 使用django-excel开源库上传、下载excel报表

需求

在平常的开发中存在上传报表文件、提供下载报表文件的功能,本次使用django-excel这个开源库来作一个下载excel报表文件的示例。html

Github仓库

django-excelhtml5

已知约束(Known constraints)

Fonts, colors and charts are not supported.python

该开源库并不支持字体、颜色、图表,这个仍是须要提早知道一下的。 若是须要支持字体、颜色、图表也只能去使用其余库了,例如:openpyxlgit

介绍

下面是一个常见开发者与用户的对话场景:github

用户:“我刚刚上传了一个excel文件,可是你的应用说不支持该类格式” 开发者:“那你上传的xlsx文件仍是csv文件?”web

用户:“我不肯定呀,我只知道我是使用Microsoft Excel保存文件的,那应该就是excel格式了吧。” 开发者:“好吧。那么这个状况是这样的,我没有被告知须要在一天内写完支持全部excel格式的功能,因此只可以先勉强使用这个功能,或者推迟这个项目几天。”数据库

django-excel 是基于 pyexcel 的,经过http协议和文件系统,能够方便地使用/生成excel文件中存储的信息。此库能够将Excel数据转换为列表list、词典dict的数据,不须要关注上述兼容各类文件类型的状况。django

当Excel文件驱动的Web应用程序交付给非开发用户时(即:团队助理、人力资源管理员等)。事实上,并非每一个人都知道(或关心)各类Excel格式之间的差别:CSV、XLS、XLSX对他们来讲都是同样的。 django-excel 这个库不是经过文件格式来训练这些用户,让这些用户很清楚知道CSV、XLS、XLSX各类格式上的差别,这是不必的,用户体验很差。而是经过提供一个通用的编程接口来帮助Web开发人员处理大部分的Excel文件格式。当要向应用程序中添加特定的Excel文件格式类型,只需安装一个额外的PyExcel插件便可。达到应用程序没有代码更改,Excel文件格式也再也不有问题的目的。编程

显著的突出功能罗列以下:json

  • excel 数据从数据库的导入导出功能
  • 转化上传excel文件的内容为python结构化数据,例如:list,dict
  • 将python结构化数据list、dict 转为excel下载文件
  • 在服务器端以excel文件的形式提供数据持久性
  • 默认支持csv、tsv、csvz、tsvz,其余格式经过如下插件支持:

A list of file formats supported by external plugins

Package name Supported file formats Dependencies Python versions
pyexcel-io csv, csvz [1], tsv, tsvz [2] 2.6, 2.7, 3.3, 3.4, 3.5, 3.6 pypy
pyexcel-xls xls, xlsx(read only), xlsm(read only) xlrdxlwt same as above
pyexcel-xlsx xlsx openpyxl same as above
pyexcel-ods3 ods pyexcel-ezodf, lxml 2.6, 2.7, 3.3, 3.4 3.5, 3.6
pyexcel-ods ods odfpy same as above

Dedicated file reader and writers

Package name Supported file formats Dependencies Python versions
pyexcel-xlsxw xlsx(write only) XlsxWriter Python 2 and 3
pyexcel-xlsxr xlsx(read only) lxml same as above
pyexcel-xlsbr xlsx(read only) pyxlsb same as above
pyexcel-odsr read only for ods, fods lxml same as above
pyexcel-odsw write only for ods loxun same as above
pyexcel-htmlr html(read only) lxml,html5lib same as above
pyexcel-pdfr pdf(read only)

Other data renderers

Package name Supported file formats Dependencies Python versions
pyexcel-text write only:rst, mediawiki, html, latex, grid, pipe, orgtbl, plain simple read only: ndjson r/w: json tabulate 2.6, 2.7, 3.3, 3.4 3.5, 3.6, pypy
pyexcel-handsontable handsontable in html handsontable same as above
pyexcel-pygal svg chart pygal 2.7, 3.3, 3.4, 3.5 3.6, pypy
pyexcel-sortable sortable table in html csvtotable same as above
pyexcel-gantt gantt chart in html frappe-gantt except pypy, same as above

In order to manage the list of plugins installed, you need to use pip to add or remove a plugin. When you use virtualenv, you can have different plugins per virtual environment. In the situation where you have multiple plugins that does the same thing in your environment, you need to tell pyexcel which plugin to use per function call. For example, pyexcel-ods and pyexcel-odsr, and you want to get_array to use pyexcel-odsr. You need to append get_array(..., library='pyexcel-odsr').

Footnotes

| [1] | zipped csv file |

| [2] | zipped tsv file |

This library makes information processing involving various excel files as easy as processing array, dictionary when processing file upload/download, data import into and export from SQL databases, information analysis and persistence. It uses pyexcel and its plugins:

  1. to provide one uniform programming interface to handle csv, tsv, xls, xlsx, xlsm and ods formats.
  2. to provide one-stop utility to import the data in uploaded file into a database and to export tables in a database as excel files for file download.
  3. to provide the same interface for information persistence at server side: saving a uploaded excel file to and loading a saved excel file from file system.

说明:其实罗列了那么多库只要随便看几眼就好,不须要去记住。由于在运行的时候,若是缺乏哪一个库,在调试的模式下就会报错,提示须要安装哪一个库,而后去安装便可。

安装

$ pip3 install django-excel
复制代码

or clone it and install it:

$ git clone https://github.com/pyexcel-webwares/django-excel.git
$ cd django-excel
$ python3 setup.py install
复制代码

配置

须要在项目的settings.py中配置以下:

# 配置django-excel
FILE_UPLOAD_HANDLERS = (
    "django_excel.ExcelMemoryFileUploadHandler",
    "django_excel.TemporaryExcelFileUploadHandler",
)
复制代码

示例

  • 由于在示例中须要操做csv 、xlsx文件,因此须要另外安装第三方库:
pip3 install pyexcel-xls
pip3 install pyexcel-xlsx
复制代码

若是未安装,在访问视图的适合就会报错,提示须要安装该库。

  • 在视图中的上传excel以及下载excel示例代码以下:
from django.http import HttpResponseBadRequest
from django.views.generic import View
from django import forms
import django_excel as excel

class UploadFileForm(forms.Form):
    file = forms.FileField()

# ex:/assetinfo/test_django_excel_upload
class TestDjangoExcelUpload(View):
    """测试使用django-excel上传文件"""

    def get(self,request):
        form = UploadFileForm()
        return render(request,'upload_form.html',context={ 'form': form })

    def post(self,request):
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            filehandle = request.FILES['file']
            return excel.make_response(filehandle.get_sheet(), "csv")
        else:
            return HttpResponseBadRequest()

# ex:/assetinfo/test_django_excel_download
class TestDjangoExcelDownload(View):
    """测试使用django-excel下载文件"""

    def get(self):
        sheet = excel.pe.Sheet([[1, 2], [3, 4]])
        return excel.make_response(sheet, "xlsx")
复制代码
  • 设置访问视图的url
from .views import *

app_name = 'assetinfo' # 设置命名空间

urlpatterns = [

    # ex:/assetinfo/test_django_excel_upload
    path('test_django_excel_upload', TestDjangoExcelUpload.as_view() , name='test_django_excel_upload'),

    # ex:/assetinfo/test_django_excel_download
    path('test_django_excel_download', TestDjangoExcelDownload.as_view() , name='test_django_excel_download'),
]
复制代码
  • 编写upload_form.html页面
<html>
<head>
    <title>{{title}}</title>
</head>
<body>
    <h1>{{header}}</h1>

    {% if form.errors %}
        <p style="color: red;">
            Please correct the error{{ form.errors|pluralize }} below.
        </p>
    {% endif %}

    <form action="{% url 'assetinfo:test_django_excel_upload' %}" enctype="multipart/form-data"  method="post">
        <table>
            {{ form.as_table }}
        </table>
        {% csrf_token %}
        <input type="submit" value="Submit">
    </form>
</body>
</html>
复制代码
  • 测试上传excel文件

执行python3 manage.py runserver启动服务,访问上传文件页面以下: http://127.0.0.1:8000/assetinfo/test_django_excel_upload

能够看到上传的excel文件转化未csv格式的文件,并提供了下载。 打开看看下载下来的csv文件,以下:

  • 测试下载excel文件

访问http://127.0.0.1:8000/assetinfo/test_django_excel_download,则会当即下载视图由list生成的excel文件以下:

打开excel查看以下:

相关文章
相关标签/搜索