[英]Uploading excel data into django without saving the file
I am a newbie to django and i'm desperate for help uploading and reading excel data without actually saving the data on the machine. 我是django的新手,我迫切需要帮助上传和阅读excel数据而不实际保存机器上的数据。 I have written some code and taken some from the research i've done online. 我已经写了一些代码并从我在网上完成的研究中得到了一些代码。
These are my questions: 这些是我的问题:
1. How do I Upload an excel file (without it being saved on the machine). 1.如何上传Excel文件(不将其保存在计算机上)。 I just want the excel file to populate some django fields and not save it. 我只是希望excel文件填充一些django字段而不保存它。
How do I make django read the columns in the excel file and feeds into some other fields on another page. 如何让django读取excel文件中的列并将其提供给另一页上的其他字段。 (How do I link them up?) (如何将它们链接起来?)
Most docs I've seen require me to hard-code the name of the excel file and its locations.IS there a way around this as I don't know where the user might be uploading from. 我见过的大多数文档都要求我对excel文件的名称及其位置进行硬编码。有一种解决方法,因为我不知道用户可能从哪里上传。 pls advice. 请咨询。
My views.py: 我的views.py:
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from credit.models import Document
from credit.forms import DocumentForm
def list(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save()
return HttpResponseRedirect(reverse('credit.views.list'))
else:
form = DocumentForm()
documents = Document.objects.all()
return render_to_response('credit/list.html',
{'documents': documents, 'form': form},
context_instance=RequestContext(request)
)
My models.py is: 我的models.py是:
class Document(models.Model):
docfile = models.FileField(upload_to='documents/')
#these are the models I want the excel columns to feed into
policies = DecimalNumberField()
capital = DecimalNumberField()
inflation = DecimalNumberField()
My forms.py is: 我的forms.py是:
import os
import xlrd
IMPORT_FILE_TYPES = ['.xls', ]
class DocumentForm(forms.Form):
docfile = forms.FileField(label='Select a file')
def clean(self):
data = super(DocumentForm, self).clean()
if 'docfile' not in data:
raise forms.ValidationError(_('The Excel file is required to proceed'))
docfile = data['docfile']
extension = os.path.splitext(docfile.name)[1]
if not (extension in IMPORT_FILE_TYPES):
raise forms.ValidationError(u'%s is not a valid Excel file. Please make sure your input file is an Excel file )' % docfile.name)
file_data = StringIO.StringIO()
for chunk in docfile.chunks():
file_data.write(chunk)
data['file_data'] = file_data.getvalue()
file_data.close()
try:
xlrd.open_workbook(file_contents=data['file_data'])
except xlrd.XLRDError, e:
raise forms.ValidationError(_('Unable to open XLS file: %s' % e))
return data
#i do not want to do this (specify the exact file name). Need an alternative
sh = xlrd.open_workbook('documents\june.xls').sheet_by_index(1)
inflation = open("inflation.txt", 'w')
policies= open("policies.txt", 'w')
capital= open("access_to_finance.txt", 'w')
try:
for rownum in range(sh.nrows):
inflation.write(str(rownum)+ " = " +str(sh.cell(rownum, 1).value)+"\n")
policies.write(str(rownum)+ " = " +str(sh.cell(rownum, 2).value)+"\n")
capital.write(str(rownum)+ " = " +str(sh.cell(rownum, 3).value)+"\n")
finally:
inflation.close()
policies.close()
capital.close()
Then I have a list.html file: 然后我有一个list.html文件:
{% if documents %}
<ul class="nav nav-tabs">
{% for document in documents %}
<li><a href="{{ document.docfile.url }}">{{ document.docfile.name }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>Click Upload to go to Upload page</p>
{% endif %}
<form action="{% url list %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload" /></p>
</form>
Answer for question 1: 问题1的答案:
If your upload file is less then FILE_UPLOAD_MAX_MEMORY_SIZE(2.5MB) , django puts the uploaded file in memory. 如果您的上传文件少于FILE_UPLOAD_MAX_MEMORY_SIZE(2.5MB) ,则django会将上传的文件放入内存中。 If your file is bigger than 2.5MB, you can change FILE_UPLOAD_MAX_MEMORY_SIZE in your settings file 如果您的文件大于2.5MB,则可以在设置文件中更改FILE_UPLOAD_MAX_MEMORY_SIZE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.