Django中从本地上传excel文件并将数据存储到数据库

Django中从本地上传excel文件并将数据存储到数据库

一、前端界面

<div class="page-container">
    <form action="{% url 'basic:uploadGrade' %}" method="post"
          enctype="multipart/form-data">
        {% csrf_token %}
        <input type="file" style="width: 50%" name="file" id="filename">
        <button class="btn btn-primary-outline radius size-S" type="submit">提交</button>
    </form>
</div>

二、views中

def uploadGrade(request):
    '''
    班级信息导入
    :param request:
    :return:
    '''
    if request.method == 'POST':
        f = request.FILES.get('file')
        excel_type = f.name.split('.')[1]
        if excel_type in ['xlsx','xls']:
            # 开始解析上传的excel表格
            wb = xlrd.open_workbook(filename=None,file_contents=f.read())
            table = wb.sheets()[0]
            rows = table.nrows  # 总行数
            try:
                with transaction.atomic():  # 控制数据库事务交易
                    for i in range(1,rows):
                        rowVlaues = table.row_values(i)
                        major = models.TMajor.objects.filter(majorid=rowVlaues[1]).first()
                        models.TGrade.objects.create(gradeid=rowVlaues[0],major=major,gradename=rowVlaues[2],memo=rowVlaues[3])
            except:
                logger.error('解析excel文件或者数据插入错误')
            return render(request,'bg/success.html',{'message':'导入成功'})
        else:
            logger.error('上传文件类型错误!')
            return render(request,'bg/failed.html',{'message':'导入失败'})
posted @ 2018-11-05 16:50  petrolero  阅读(8185)  评论(0编辑  收藏  举报