How to parse excel files uploaded by users with django

  • 2020-06-12 10:01:21
  • OfStack

preface

When we are working, we have the requirement that a user uploads a fixed excel form to the website, and then the program takes the debt to parse the content and process it. Recently, I met them in my work, so I want to share the summary of the solution process for your reference and study. Let's start with a detailed introduction.

Take a simple chestnut. Let's say we have an HTML:


<!DOCTYPE html>
<html>
 <head>
 <meta charset="utf-8">
 </head>
 <body>
 <p> upload EXCEL form </p>
 <form class="" action="" method="post" enctype="multipart/form-data" >
  {% csrf_token %}
  <input type="file" name="excel">
  <input type="submit" value=" upload ">
 </form>
 </body>
</html>

forms. py file content is as follows, prepare 1 simple judgment suffix verification:


# coding=utf-8
from django import forms
from django.utils.translation import gettext as _
from django.core.exceptions import ValidationError
def 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]) # Custom validation is used here 

I'm using the xlrd library here to process the excel table. Just install it using pip. There are two ways to process an POST request at this point:

The excel uploaded by the user is stored on disk and read to xlrd for processing. excel reads uploaded by the user are read directly in memory and handed over to xlrd.

I use the second option here -- without changing the django default settings.py configuration, the user uploads a file of the InMemoryUploadedFile type, which has one read() views. py can read contents directly from memory without writing to 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 here 
 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 can be said for any other file type if you don't need to save the user's uploaded files to your hard drive. Here are two resources related to django processing excel:

django-excel (local download) determines the user's 3-square library in excel format https: / / assist - software net blog/how - export - excel - files - python - django - application shows you how to export excel articles

conclusion


Related articles: