1、在一些场景中经常需要管理员批量导入数据,先将数据写到excel表格中,再上传到系统上,最后将excel中的数据批量导入到系统的数据库中。

1.1、test.xlsx文件数据格式

首行的名字:必须是数据库对应的字段名,这样才能使用**打散字典,实现快速创建。

 

2、视图类如何实现

class TestExcelView(ViewSet):
    authentication_classes = []
    permission_classes = []
    throttle_classes = []
    @action(methods=['get'],detail=False)
    def testexcel(self,request):
        path=os.path.join(settings.MEDIA_ROOT,'students_excels','test.xlsx')
        wb = openpyxl.load_workbook(path)
        ws = wb.active
        max_row = ws.max_row
        max_column = ws.max_column
        all_lis=[]
        lis=[]
        for row in range(1,max_row+1):
            dic={}
            for column in range(1,max_column+1) :
                if row==1:
                    #将首行的东西加到列表中
                    lis.append(ws.cell(row,column).value)
                    continue
                #将行首标题作为的key,其余行对应列作为value,拿到dict,一行就一个dict
                dic.setdefault(lis[column-1],ws.cell(row,column).value)
            if row>1:
                #首行的dict就是空,不需要加入
                all_lis.append(dic)
        try:
            for user_dic in all_lis:
                models.User.objects.create_user(**user_dic)
            return ApiResponse(msg='创建用户成功',data=all_lis)
        except:
            return ApiResponse(data={'erroe':'excel文件有问题,先检查文件格式'})

3、all_list的数据格式

一行就是一条数据库的记录,创建用户时直接 **dic,就可以实现创建记录。

其他批量的生成的数据原理也是一样的。

 

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐