在Django中上传Excel数据而不保存文件

4 投票
1 回答
4706 浏览
提问于 2025-04-27 22:15

我刚接触django,急需帮助,想要上传和读取Excel数据,但不想把数据保存到机器上。我写了一些代码,也参考了一些网上的资料。

我有以下几个问题:
1. 我该如何上传一个Excel文件(不保存到机器上)?我只想让这个Excel文件填充一些django的字段,而不保存它。

  1. 我该如何让django读取Excel文件中的列,并把这些数据填充到另一个页面的字段中?(我该如何把它们连接起来?)

  2. 我看到的大多数文档都要求我硬编码Excel文件的名称和位置。有没有什么办法可以避免这样,因为我不知道用户可能从哪里上传文件。请给我一些建议。

我的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)
)

我的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()

我的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()

然后我有一个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>
暂无标签

1 个回答

1

问题1的回答:

如果你上传的文件小于 FILE_UPLOAD_MAX_MEMORY_SIZE(2.5MB),那么Django会把这个上传的文件放在内存里。如果你的文件超过了2.5MB,你可以在设置文件中修改 FILE_UPLOAD_MAX_MEMORY_SIZE 的值。

撰写回答