コード例 #1
0
 def _load_unique_items_to_code(self, workbook):
     """
     Load in the terms
     TODO: Refactor this!!
     """
     terminology = {}
     if isinstance(workbook, openpyxl.workbook.Workbook):
         for sheet_name in ('Fields to be Coded', 'Fields Coded'):
             sheet = workbook.get_sheet_by_name(sheet_name)
             for (idx, content) in enumerate(sheet.rows):
                 if idx == 0:
                     # ignore header
                     continue
                 if not si(content[0]):
                     # blank rows
                     continue
                 if '|' in si(content[0]):
                     # multiple terms, split 'em
                     terms = [x.strip() for x in si(content[0]).split('|')]
                     values = [x.strip() for x in si(content[1]).split('|')]
                     if not len(terms) == len(values):
                         print 'Error in mapping: %s => %s (Not a match in numbers)' % (si(content[0]), si(content[1]))
                     else:
                         terminology.update(dict(zip(terms, values)))
                     pass
                 else:
                     # Map a 'None' to ''
                     terminology[si(content[0])] = {None : '',
                                                    'None' : ''}.get(si(content[1]), si(content[1]))
         
     else:
         for sheet_name in ('Fields to be Coded', 'Fields Coded'):
             sheet = workbook.sheet_by_name(sheet_name)
             for row in range(1, sheet.nrows):
                 content = sheet.row_values(row)
                 if '|' in si(content[0]):
                     terms = [x.strip() for x in si(content[0]).split('|')]
                     values = [x.strip() for x in si(content[1]).split('|')]
                     if not len(terms) == len(values):
                         print 'Error in mapping: %s => %s (Not a match in numbers)' % (si(content[0]), si(content[1]))
                     else:
                         terminology.update(dict(zip(terms, values)))
                 else:
                     terminology[si(content[0])] = {None : '', 'None' : ''}.get(si(content[1]), si(content[1]))
     return terminology
コード例 #2
0
def ca_import(request):
    uploadform = UploadFileForm(None)
    if request.method == 'POST':
        uploadform = UploadFileForm(request.POST, request.FILES)
        if uploadform.is_valid():
            file = uploadform.cleaned_data['docfile']
            workbook = openpyxl.load_workbook(filename=file, read_only=True)
            # Get name of the first sheet and then open sheet by name
            first_sheet = workbook.get_sheet_names()[0]
            worksheet = workbook.get_sheet_by_name(first_sheet)
            data = []
            # data2 = []

            try:
                #  if uploadform.cleaned_data.get('seller') == 'True':
                #     sel=True
                #  else:
                #     sel=False
                for row in worksheet.iter_rows(
                        row_offset=1):  # Offset for header
                    # stock = Stocks()
                    part = Parts()
                    part.user = request.user
                    # stock.name = row[0].value
                    Cars.objects.get_or_create(
                        carname=str(row[0].value)
                    )  #Save new car in Car table if not available (for autocomplete)
                    part.car = Cars.objects.get(
                        carname=str(row[0].value)
                    )  #car is a foreign key filed related to Car table
                    # stock.number = row[1].value
                    part.partname = row[1].value
                    # stock.suffix = row[2].value
                    # stock.pic = row[2].value
                    # stock.brand = row[3].value.upper()
                    part.description = row[2].value
                    # stock.comment = row[4].value
                    part.price = row[3].value
                    # stock.date = datetime.today()
                    # stock.confirm = 'approved'
                    # stock.seller = sel
                    data.append(part)
            #Bulk create data
            # Stocks.objects.bulk_create(data)
                Parts.objects.bulk_create(data)

                #save for autocomplete
                # for row in range(2,worksheet.max_row+1):
                #    for column in "A":  #Here you can add or reduce the columns
                #        cell_name = "{}{}".format(column, row)
                #        Cars.objects.get_or_create(carname=str(worksheet[cell_name].value))

                messages.success(request,
                                 "با موفقیت ثبت گردید",
                                 extra_tags="saveexcel")
            except:
                messages.error(
                    request,
                    _('نکات ذیل را برای ثبت فایل درنظر بگیرید. از خالی نبود فیلدهای name و brand اطمینان حاصل کنید'
                      ),
                    extra_tags="excelerror")

    return render(request, 'BallbearingSite/excelfile.html',
                  {'uploadform': uploadform})
コード例 #3
0
    def _load_template_xml(self, filename):
        """
        use a different reader
        """
        try:
            workbook = openpyxl.reader.excel.load_workbook(filename)
        except Exception, e:
            import traceback, sys
            print 'Failed to open %s : %s' % (filename, e)
            traceback.print_tb(sys.exc_info()[2])
            return
        terminology = {}
        if 'Fields to be Coded' in workbook.get_sheet_names():
            terminology = self._load_unique_items_to_code(workbook)
        else:    
            sheet = workbook.get_sheet_by_name('Terms')
            for (idx, row) in enumerate(sheet.rows):
                if idx == 0:
                    # ignore header
                    continue
                if not si(row[0]):
                    # blank rows
                    continue
                terminology[si(row[0])] = {None : ''}.get(si(row[1]), si(row[1]))
        print 'Loaded %s terms' % len(terminology)
        return terminology

    def _load_unique_items_to_code(self, workbook):
        """
        Load in the terms
        TODO: Refactor this!!
コード例 #4
0
 def _set_sheet_active(self, sheet_name, workbook):
     activeSheet = workbook.get_sheet_by_name(name=sheet_name)
     return activeSheet