How to parse the excel File Uploaded by the user using django, djangoexcel
Preface
In our work, we have this requirement: the user uploads a fixed excel form to the website, and then parses and processes the program liabilities. I recently encountered this problem in my work, so I want to summarize and share the Solution Process for your convenience. I will not talk about it here. Let's take a look at the details:
For example, we have an HTML:
<! DOCTYPE html>
The content of the forms. py file is as follows:
# Coding = utf-8from django import formsfrom django. utils. translation import gettext as _ from django. core. exceptions import ValidationErrordef validate_excel (value): if value. name. split ('. ') [-1] not in ['xls', 'xlsx']: raise ValidationError (_ ('invalid File Type: % (value) s '), params = {'value': value},) class UploadExcelForm (forms. form): excel = forms. fileField (validators = [validate_excel]) # use custom verification here
I use the xlrd library here to process the excel table and use pip to install it. There are two methods to process POST requests:
- Store the excel files uploaded by the user to the disk and then read them to xlrd for processing.
- Read the excel File Uploaded by the user directly in the memory and submit it to xlrd for processing.
Here I use the second method -- without modifying the default settings. py configuration of django, the File Uploaded by the user is actually of the InMemoryUploadedFile type, which hasread()Methods, so the views. py can directly read the content in the memory instead of writing to the disk:
Def post (self, request, * args, ** kwargs): form = UploadExcelForm (request. POST, request. FILES) if form. is_valid (): wb = xlrd. open_workbook (filename = None, file_contents = request. FILES ['excel ']. read () # The key point is that table = wb. sheets () [0] row = table. nrows for I in xrange (1, row): col = table. row_values (I) print col return HttpResponse ("OK ")
The same applies to other file types. If you do not need to save the files uploaded by the user to the hard disk, you can do this. Here we record two resources related to django's excel processing:
- Django-excel (local download) identifies a third-party library in excel format
- Https://assist-software.net/blog/how-export-excel-files-python-django-application explains how to export an excel article
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.