前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Django 2.1.7 使用django-excel上传、下载excel报表

Django 2.1.7 使用django-excel上传、下载excel报表

作者头像
Devops海洋的渔夫
发布2019-10-09 15:27:46
3.9K0
发布2019-10-09 15:27:46
举报
文章被收录于专栏:Devops专栏Devops专栏

需求

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

Github仓库

django-excel

已知约束(Known constraints)

Fonts, colors and charts are not supported.

该开源库并不支持字体、颜色、图表,这个还是需要提前知道一下的。 如果需要支持字体、颜色、图表也只能去使用其他库了,例如:openpyxl

介绍

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

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

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

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

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

显著的突出功能罗列如下:

  • 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)

xlrd, xlwt

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.

说明:其实罗列了那么多库只要随便看几眼就好,不需要去记住。因为在运行的时候,如果缺少哪个库,在调试的模式下就会报错,提示需要安装哪个库,然后去安装即可。

安装

代码语言:javascript
复制
$ pip3 install django-excel

or clone it and install it:

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

配置

需要在项目的settings.py中配置如下:

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

示例

  • 因为在示例中需要操作csv 、xlsx文件,所以需要另外安装第三方库:
代码语言:javascript
复制
pip3 install pyexcel-xls
pip3 install pyexcel-xlsx

如果未安装,在访问视图的适合就会报错,提示需要安装该库。

  • 在视图中的上传excel以及下载excel示例代码如下:
代码语言:javascript
复制
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
代码语言:javascript
复制
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页面
代码语言:javascript
复制
<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查看如下:
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.10.09 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 需求
  • Github仓库
    • 已知约束(Known constraints)
      • 介绍
      • 安装
      • 配置
      • 示例
      相关产品与服务
      文件存储
      文件存储(Cloud File Storage,CFS)为您提供安全可靠、可扩展的共享文件存储服务。文件存储可与腾讯云服务器、容器服务、批量计算等服务搭配使用,为多个计算节点提供容量和性能可弹性扩展的高性能共享存储。腾讯云文件存储的管理界面简单、易使用,可实现对现有应用的无缝集成;按实际用量付费,为您节约成本,简化 IT 运维工作。
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档