使用django-excel

时间:2017-01-13 21:51:24

标签: python django django-excel

我使用Django构建网站,我想创建一个功能,用户可以通过Excel工作表上传信息并填充数据库。所以我安装了django-excel包并按照示例进行操作:

settings.py

FILE_UPLOAD_HANDLERS = ("django_excel.ExcelMemoryFileUploadHandler",
                    "django_excel.TemporaryExcelFileUploadHandler")

urls.py

url(r'^import_sheet/', views.import_sheet, name="import_sheet"),

views.py

class UploadFileForm(forms.Form):
   file = forms.FileField()

def upload(request):
if request.method == "POST":
    form = UploadFileForm(request.POST, request.FILES)
    if form.is_valid():
        filehandle = request.FILES['file']
        return excel._make_response(filehandle.get_sheet(),"xslx",file_name="download")  
    else:
        form = UploadFileForm()
        return render(request,'upload_form.html',{
            'form': form,
            'title': 'Excel file upload',
            'header': 'Please choose a valid excel file'
        })

def import_sheet(request):
    if request.method == "POST":
        form = UploadFileForm(request.POST,
                          request.FILES)
        if form.is_valid():
            request.FILES['file'].save_to_database(
                model= quote_input,
                mapdict= ["value_date", "value", "type", 'name'])
            return HttpResponse("OK")
        else:
            return HttpResponseBadRequest()
    else:
        form = UploadFileForm()
    return render(
        request,
        'upload_form.html',
        {'form': form})

models.py

class quote_input(models.Model):
    value_date  = models.DateField()
    value       = models.FloatField()
    type        = models.TextField(max_length=254)
    name        = models.TextField(max_length=254)
    # link
    fund            = models.ForeignKey(Fund)
    benchmark       = models.ForeignKey(Benchmark)
    factor          = models.ForeignKey(Factors)
    stress_factor   = models.ForeignKey(Stress_Factors)

当我通过上传基本Excel工作表尝试此代码时: enter image description here

我得到了一个OK(HttpResponse)但是当我查看数据库时,我没有上传任何内容。

有人有同样的问题吗?或者可以提供另一个我可以使用的例子?另一种方法?

另一个问题:在django-excel文档中,有一个关于函数“choice_func”的引用,它被定义为自定义格式化函数。任何人都可以提供有关此功能的更多信息吗?

2 个答案:

答案 0 :(得分:3)

这是我的代码的一个版本,我使用xlrd库。

import re
import xlrd

from agencies.models import Invite
from extras.permissions import send_mail_wrapper
from sms.sms_api import send_sms


def handle_uploaded_file(request, f):
    book = xlrd.open_workbook(file_contents=f.read())
    for sheet in book.sheets():
        number_of_rows = sheet.nrows
        number_of_columns = sheet.ncols

        for row in range(1, number_of_rows):

            first_name = (sheet.cell(row, 0).value)
            last_name = (sheet.cell(row, 1).value)
            email = (sheet.cell(row, 2).value)

            phone_cell = (sheet.cell(row, 3).value)
            if phone_cell:
                phone = re.sub("[^0-9]", "", str(phone_cell))
            else:
                phone = ""
            gender = (sheet.cell(row, 4).value).upper()

            if email != "":
                invite, created = Invite.objects.get_or_create(agency=request.user.agency, email=email)

                if email and created:
                    send_sms(phone)
                    send_mail_wrapper(
                        "You \'ve been invited", 'email/invite_email.html',
                        {}, [email], from_email='Casey <success@email.com>')

观点:

class StudentBulkAddView(ListView):
    model = Student
    template_name = 'student_add.html'

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(DashboardStudentBulkAddView, self).dispatch(*args, **kwargs)

    def post(self, request):
        if self.request.user.is_authenticated:
            try:
                handle_uploaded_file(request, request.FILES['student_file'])
                success = True

模板:

                <form action="{% url 'students:student_dashboard_bulk_invite' %}" method="POST"
                      enctype="multipart/form-data">
                    <div class="form-settings notes-form">
                        {% csrf_token %}
                        {{ upload_form }}
                        <button id="invite-tutor-btn" class="btn btn-primary margin-top"
                                data-loading-text="Loading..." type="submit">Save
                        </button>
                    </div>
                </form>

答案 1 :(得分:3)

我认为您需要做的就是:

def upload(request):
    form = None
    if request.method == "POST":
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            filehandle = request.FILES['file']
            # call import_sheet to import the sheet into your database
            return import_sheet(request)  
    form = form or UploadFileForm()
    return render(request,'upload_form.html',{
        'form': form,
        'title': 'Excel file upload',
        'header': 'Please choose a valid excel file'
    })