在平常的開發中存在上傳報表文件、提供下載報表文件的功能,本次使用django-excel這個開源庫來作一個下載excel報表文件的示例。html
django-excelhtml5
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
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'),
]
複製代碼
<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>
複製代碼
執行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查看以下: