码迷,mamicode.com
首页 > Web开发 > 详细

django上传excel文件

时间:2019-03-20 16:01:39      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:filename   eid   with   turn   cti   upload   开始   row   django   

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‘:‘导入失败‘})

  

django上传excel文件

标签:filename   eid   with   turn   cti   upload   开始   row   django   

原文地址:https://www.cnblogs.com/majianyu/p/10565227.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!