【问题标题】:Django-importing excel file into django modelsdjango-将excel文件导入django模型
【发布时间】:2018-02-12 18:08:21
【问题描述】:

我需要用户通过提供的表单上传一个 excel 文件,我需要处理上传的 excel 文件以将数据保存在我的模型中。

models.py

class Patient_Record(models.Model):

    Patient_id=models.IntegerField(unique=True)
    Patient_sex=models.CharField(max_length=1,choices=Gender)
    Patient_name=models.CharField(max_length=20)
    Patient_sugar=models.DecimalField(decimal_places=3,max_digits=6)
    Patient_chlorestrol=models.DecimalField(decimal_places=3,max_digits=6)
    Patient_iron=models.DecimalField(decimal_places=3,max_digits=6)
    Patient_haemoglobin=models.DecimalField(decimal_places=3,max_digits=6)

    def __str__(self):
        return self.pat_name

我有简单的表格来上传文件。

<form method="POST" class="post-form" action="../Uploaded_file" enctype="multipart/form-data" name="myfile">{% csrf_token %}
                    {{ upload_form.as_p }}
<input type="submit" value="Upload" name="Upload" class="btn  btn-primary">
</form>

有人可以帮助我使用 POST 解析 Excel 文件的代码到此模型。

我尝试了许多不同的方法,但都没有成功。

【问题讨论】:

    标签: python django excel


    【解决方案1】:

    您需要 xlrd 库才能从 Excel 工作表中提取数据。 查看以下链接https://pypi.python.org/pypi/xlrd

    这是示例 sn-p。您可以根据自己的代码进行修改。

    在 Forms.py 中创建一个具有以下字段的模型表单。

    class UpdateDetailsForm(forms.Form):
     excel_file = forms.FileField(label='Excel File',required=False,validators=[validate_file_extension])
    

    然后在对应的views.py中

    def update_details(request):
      message=''
     if request.method == 'POST':
      form = UpdateDetailsForm(request.POST,request.FILES)
      if form.is_valid():
       #import your django model here like from django.appname.models import model_name
       excel_file = request.FILES['excel_file']
       i=0
       try:
        import os
        import tempfile
        import xlrd
        fd, tmp = tempfile.mkstemp()
        with os.fdopen(fd, 'w') as out:
          out.write(excel_file.read())
        book=xlrd.open_workbook(fd)
        sh = book.sheet_by_index(0)          
        for rx in range(1,sh.nrows):
            obj=Patient_Record(Patient_id=str(sh.row(rx)[0].value),Patient_sex=str(sh.row(rx)[1].value)) # similiary populate according to your  model
            obj.save()
            i=i+1;
       finally:
        os.unlink(tmp)
      else:
        message='Invalid Entries'
     else:
        form = UpdateDetailsForm()
     return render_to_response('admin/import_data.html', {'form':form,'message':message},context_instance=RequestContext(request))
    

    【讨论】:

    • 什么是 UpdateDetailsForm ?
    • 是forms.py中的类名。检查编辑的版本。您可以如上所示在您的应用程序中的 forms.py 中创建类 Updatedetailsform 并使用它来上传 excel 工作表。然后,您需要 xlrd 库从工作表中提取数据。
    • 谢谢我明白了。但是你为什么要将所有内容都转换为 string ?由于 Patient_id 是一个整数,它不会引发错误吗?
    • 得到一个 typeError write() 参数必须是 str,而不是 bytes
    • 这只是一个示例代码。我刚刚使用了我工作代码中的一小部分。您必须根据您的字段类型进行更新。
    【解决方案2】:

    在 Python 3.6 和 Django 2.0 中出现以下错误 异常类型:PermissionError 异常值:[WinError 32]

    def upload_file(request):
        message=''
        if request.method == 'POST':
            form = FormUploadFileData(request.POST, request.FILES)
            if form.is_valid():
                from projects.models import Project
                excel_file = request.FILES['excel_file']
                try:
                    import os
                    import tempfile
                    import xlrd
                    fd, tmp = tempfile.mkstemp() # create two temporary file
                    with os.open(fd, 'wb') as out: # create new file objects
                        out.write(excel_file.read())
                    book = xlrd.open_workbook(fd)
                    sheet = book.sheet_by_index(0)
                    obj=Project(
                        project_title = sheet.cell_value(rowx=1, colx=1),
                        project_sector = sheet.cell_value(rowx=2, colx=1),
                        project_location = sheet.cell_value(rowx=3, colx=1),
                        project_tot_cost = sheet.cell_value(rowx=4, colx=1),
                        project_descr = sheet.cell_value(rowx=5, colx=1),
                        project_fund = sheet.cell_value(rowx=6, colx=1),
                        project_cofin = sheet.cell_value(rowx=7, colx=1),
                        project_applicant = sheet.cell_value(rowx=8, colx=1)
                    )
                    obj.save()
                finally:
                    os.unlink(tmp)
            else:
                message='Invalid Entries'
        else:
            form = FormUploadFileData()
        return render(request,'upload.html', {'form':form,'message':message})
    

    【讨论】:

      【解决方案3】:

      提出的解决方案存在问题:

      book=xlrd.open_workbook(fd) 应该是 book=xlrd.open_workbook(tmp) 作为文件路径的open_workhook search

      [使用 Python 3.6、Django 2.0]

      excel_file = request.FILES['excel_file']
              import os
              import tempfile
              import xlrd
              fd, path = tempfile.mkstemp() #  mkstemp returns a tuple: an integer (index) called file descriptor used by OS to refer to a file and its path
              try:
                  with os.fdopen(fd, 'wb') as tmp:
                      tmp.write(excel_file.read())
                  book = xlrd.open_workbook(path)
                  sheet = book.sheet_by_index(0)
                  obj=Project(
                      project_title = sheet.cell_value(rowx=1, colx=1),
                      project_sector = sheet.cell_value(rowx=2, colx=1),
                      project_location = sheet.cell_value(rowx=3, colx=1),
                      project_tot_cost = sheet.cell_value(rowx=4, colx=1),
                      project_descr = sheet.cell_value(rowx=5, colx=1),
                      project_fund = sheet.cell_value(rowx=6, colx=1),
                      project_cofin = sheet.cell_value(rowx=7, colx=1),
                      project_applicant = sheet.cell_value(rowx=8, colx=1)
                  )
                  obj.save()
              finally:
                  os.remove(path)
      

      【讨论】:

        猜你喜欢
        • 2012-03-27
        • 2019-01-01
        • 2017-02-19
        • 2012-04-16
        • 2018-09-26
        • 2014-04-14
        • 1970-01-01
        • 2020-12-14
        • 2018-02-23
        相关资源
        最近更新 更多