在日常的开发中存在上传报表文件、提供下载报表文件的功能,本次使用django-excel这个开源库来做一个下载excel报表文件的示例。
django-excel
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文件格式也不再有问题的目的。
显著的突出功能罗列如下:
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:
说明:其实罗列了那么多库只要随便看几眼就好,不需要去记住。因为在运行的时候,如果缺少哪个库,在调试的模式下就会报错,提示需要安装哪个库,然后去安装即可。
$ 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",
)
pip3 install pyexcel-xls
pip3 install pyexcel-xlsx
如果未安装,在访问视图的适合就会报错,提示需要安装该库。
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")
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'),
]
{{title}}
{{header}}
{% if form.errors %}
Please correct the error{{ form.errors|pluralize }} below.
{% endif %}
执行python3 manage.py runserver
启动服务,访问上传文件页面如下:
http://127.0.0.1:8000/assetinfo/test_django_excel_upload
可以看到上传的excel文件转化未csv格式的文件,并提供了下载。
打开看看下载下来的csv文件,如下:
访问http://127.0.0.1:8000/assetinfo/test_django_excel_download,则会立即下载视图由list生成的excel文件如下:
打开excel查看如下: