gpt4 book ai didi

python - 使用 django-excel 通过 Excel 工作表上传数据

转载 作者:太空宇宙 更新时间:2023-11-04 08:00:05 25 4
gpt4 key购买 nike

我使用 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})

模型.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”的引用,它被定义为自定义格式化函数。任何人都可以提供有关此功能的更多信息吗?

最佳答案

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

和 View :

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>

关于python - 使用 django-excel 通过 Excel 工作表上传数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41643996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com