Django Excel, CSV 파일 처리

5541 단어 DjangoExcelCSV
1 .Excel 파일 작업:
  • 프론트 데스크톱을 통해 Excel 파일을 전송하여 분석
  •  
    import xlrd
    
     def create(self, request, *args, **kwargs):
            try:
                with transaction.atomic():
                    files = request.data
                    file = files['file']
                    wb = xlrd.open_workbook(filename=None, file_contents=file.read())  #        ,file_contents     
                    table = wb.sheets()[0]   #     sheet,       (   sheet )
                    nrows = table.nrows  #   
                    list = []
    
                    for i in range(1, nrows):     #      ,    
                        rowValues = table.row_values(i)  #      
                        #           float ,       
                        t = xlrd.xldate_as_tuple(rowValues[0], 0)   
                        date = datetime.datetime(*t)
                        cell = date.strftime('%Y-%m-%d %H:%M:%S')  
                        operatorId = str(int(rowValues[3]))
                        list.append(models.ThicknessDataModel(DateTime=cell, ProductName=rowValues[1], TimeNode=rowValues[2]
                                                              , OperatorId=operatorId, SampleSN=rowValues[4], FixtureSn=rowValues[5]
                                                              , result=rowValues[6], Thickness=rowValues[7], Voltage=rowValues[8]
                                                              , Impedance=rowValues[9]))
                        # models.ThicknessDataModel.objects.create(DateTime=cell, ProductName=rowValues[1], TimeNode=rowValues[2]
                        #                                       , OperatorId=rowValues[3], SampleSN=rowValues[4], FixtureSn=rowValues[5]
                        #                                       , result=rowValues[6], Thickness=rowValues[7], Voltage=rowValues[8]
                        #                                       , Impedance=rowValues[9])
                    models.ThicknessDataModel.objects.bulk_create(list)
                    return ReturnData(statusCode=status.HTTP_200_OK, message=_('  '))
    
            except Exception as e:
                logger_supplier.error(e)
                return ReturnData(statusCode=status.HTTP_400_BAD_REQUEST, message=_('  '))
    

    2. CSV 파일 작업:
  • 로컬 파일 분석
  •  
        def create(self, request, *args, **kwargs):
            try:
                with transaction.atomic():
                    with open(os.path.join(os.path.dirname(os.path.abspath(__file__)) +'/  .csv')) as f_csv:     #      
                        table = csv.reader(f_csv)   #  CSV    
                        list = []
                        headings = next(table)    #        
                        for rowValues in table:
                            print(rowValues)
                            # rowValues = table.row_values(i)  #      
                            #           2019-3-22 14:21,       
                            cell = datetime.datetime.strptime(rowValues[0], "%Y-%m-%d %H:%M").strftime(
                                "%Y-%m-%d %H:%M:%S")
                            list.append(models.ThicknessDataModel(DateTime=cell, ProductName=rowValues[0], TimeNode='test'    #rowValues[2]
                                                                  , OperatorId=rowValues[1], SampleSN=rowValues[2], FixtureSn=rowValues[3]
                                                                  , result=rowValues[4], Thickness=rowValues[5], Voltage=rowValues[6]
                                                                  , Impedance=rowValues[7]))
                        models.ThicknessDataModel.objects.bulk_create(list)
                    return ReturnData(statusCode=status.HTTP_200_OK, message=_('  '))
    
            except Exception as e:
                logger_supplier.error(e)
                return ReturnData(statusCode=status.HTTP_400_BAD_REQUEST, message=_('  '))
    
    
  • 프론트 데스크톱에서 전송된 CSV 파일 분석
  •  
        def create(self, request, *args, **kwargs):
            try:
                with transaction.atomic():
                    files = request.data
                    csv_file = request.FILES['file']
                    csv_file.seek(0)     #          
                    file_data = csv_file.read().decode('utf-8')
                    lines = file_data.split('\r')
                    list=[]
                    for line in lines[1:]:     #               
                        rowValues = line.split(',')  #      
                            #           2019-3-22 14:21,       
                        cell = datetime.datetime.strptime(rowValues[0], "%Y-%m-%d %H:%M").strftime(
                            "%Y-%m-%d %H:%M:%S")
                        list.append(models.ThicknessDataModel(DateTime=cell, ProductName=rowValues[0].strip() , TimeNode='test'    #rowValues[2]
                                                              , OperatorId=rowValues[1].strip() , SampleSN=rowValues[2].strip(), FixtureSn=rowValues[3].strip()
                                                              , result=rowValues[4].strip(), Thickness=rowValues[5].strip(), Voltage=rowValues[6].strip()
                                                              , Impedance=rowValues[7].strip()))
                        models.ThicknessDataModel.objects.bulk_create(list)
                    return ReturnData(statusCode=status.HTTP_200_OK, message=_('  '))
    
            except Exception as e:
                logger_supplier.error(e)
                return ReturnData(statusCode=status.HTTP_400_BAD_REQUEST, message=_('  '))

    전재:https://www.jianshu.com/p/0d15ed85df2b

    좋은 웹페이지 즐겨찾기