使用 django-excel 通过 Excel sheet 上传数据

Upload data via Excel sheet using django-excel

我使用 Django 构建了一个网站,我想创建一个功能,用户可以通过 excel sheet 上传信息并填充数据库。所以我安装了 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 sheet 来尝试此代码时:

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

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

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

这是我的代码版本,我使用 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>

我想你需要做的就是:

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'
    })