def read_sklad_data(cfg0):
    priceFName = cfg0.get('basic', 'filename2_new')
    cfg = config_read('sklad.cfg')
    sheetName = 'sklad'
    log.debug('Reading file ' + priceFName)
    book, sheet = sheetByName(fileName=priceFName, sheetName=sheetName)
    if not sheet:
        log.error("Нет листа " + sheetName + " в файле " + priceFName)
        return False
    if not sheet:
        log.error("Нет листа " + sheetName + " в файле " + priceFName)
        return False
    log.debug("Sheet   " + sheetName)
    out_cols = cfg.options("cols_out")
    in_cols = cfg.options("cols_in")
    out_template = {}
    for vName in out_cols:
        out_template[vName] = cfg.get("cols_out", vName)
    in_cols_j = {}
    for vName in in_cols:
        in_cols_j[vName] = cfg.getint("cols_in", vName)

    recOut = {}
    sklad_data = {}
    for i in range(1, sheet.max_row + 1):  # xlsx
        #    for i in range(1, sheet.nrows):                                     # xls
        i_last = i
        try:
            impValues = getXlsxString(sheet, i, in_cols_j)  # xlsx
            #            impValues = getXlsString(sheet, i, in_cols_j)              # xls
            if (impValues['код_']
                    in ('', 'Partnumber', 'Part No.')):  # Пустая строка
                continue
            else:  # Обычная строка
                if impValues['транзит_'] != '':
                    impValues['транзит_'] = 'транзит ' + impValues['транзит_']
                for outColName in out_template.keys():
                    shablon = out_template[outColName]
                    for key in impValues.keys():
                        if shablon.find(key) >= 0:
                            shablon = shablon.replace(key, impValues[key])

                    recOut[outColName] = shablon.strip()

                sklad_data[impValues['код_']] = recOut['наличие']

        except Exception as e:
            print(e)
            if str(e) == "'NoneType' object has no attribute 'rgb'":
                pass
            else:
                log.debug('Exception: <' + str(e) + '> при обработке строки ' +
                          str(i) + '.')

    log.info('Обработано ' + str(i_last) + ' строк.')
    print(sklad_data)
    return sklad_data
예제 #2
0
def convert_excel2csv(cfg):
    csvFName = cfg.get('basic', 'filename_out')
    priceFName = cfg.get('basic', 'filename_in')
    sheetName = cfg.get('basic', 'sheetname')
    subGrpFontSize = int(cfg.get('group', 'subGrpFontSize'))
    grpFontSize = int(cfg.get('group', 'grpFontSize'))
    subgrp = ''
    grp = ''

    log.debug('Reading file ' + priceFName)
    sheet = sheetByName(fileName=priceFName, sheetName=sheetName)
    if not sheet:
        log.error("Нет листа " + sheetName + " в файле " + priceFName)
        return False
    log.debug("Sheet   " + sheetName)
    out_cols = cfg.options("cols_out")
    in_cols = cfg.options("cols_in")
    out_template = {}
    for vName in out_cols:
        out_template[vName] = cfg.get("cols_out", vName)
    in_cols_j = {}
    for vName in in_cols:
        in_cols_j[vName] = cfg.getint("cols_in", vName)

    #csvFNameRUR =csvFName[:-4]+'_RUR'+csvFName[-4:]
    #csvFNameEUR =csvFName[:-4]+'_EUR'+csvFName[-4:]
    csvFNameUSD = csvFName[:-4] + '_USD' + csvFName[-4:]
    #outFileRUR = open( csvFNameRUR, 'w', newline='', encoding='CP1251', errors='replace')
    #outFileEUR = open( csvFNameEUR, 'w', newline='', encoding='CP1251', errors='replace')
    outFileUSD = open(csvFNameUSD,
                      'w',
                      newline='',
                      encoding='CP1251',
                      errors='replace')
    #csvWriterRUR = csv.DictWriter(outFileRUR, fieldnames=out_cols )
    #csvWriterEUR = csv.DictWriter(outFileEUR, fieldnames=out_cols )
    csvWriterUSD = csv.DictWriter(outFileUSD, fieldnames=out_cols)
    #csvWriterRUR.writeheader()
    #csvWriterEUR.writeheader()
    csvWriterUSD.writeheader()

    recOut = {}
    '''                        # Блок проверки свойств для распознавания групп XLSX
    for i in range(1, 15):                                                         
        i_last = i
        ccc = sheet.cell( row=i, column=in_cols_j['группа_'] )
        print(i, ccc.value)
        print(ccc.font.name, ccc.font.sz, ccc.font.b, ccc.font.i, 'ccc.font.color.rgb, ''------', ccc.fill.fgColor.rgb)
        print('------')
    return
    '''
    for i in range(2, sheet.max_row + 1):  # xlsx
        #   for i in range(2, sheet.nrows) :                                     # xls
        i_last = i
        try:
            impValues = getXlsxString(sheet, i, in_cols_j)  # xlsx
            #impValues = getXlsString(sheet, i, in_cols_j)               # xls
            #print( impValues )
            if   sheet.cell( row=i, column=in_cols_j['группа_']).font.bold ==True and \
                 sheet.cell( row=i, column=in_cols_j['группа_']).font.sz   ==grpFontSize:     # группа
                #print(sheet.cell( row=i, column=in_cols_j['код_']).fill.fgColor.indexed)
                #col2 = sheet.cell( row=i, column=in_cols_j['код_']).value.strip()
                #t = col2.rpartition(' ')
                grp = impValues['группа_']
                subgrp = ''
                continue
            elif sheet.cell( row=i, column=in_cols_j['группа_']).font.bold ==True and \
                 sheet.cell( row=i, column=in_cols_j['подгруппа']).font.sz==subGrpFontSize: # подгруппа
                subgrp = impValues['подгруппа']
                continue
            elif impValues[
                    'цена1'] == '0':  # (ccc.value == None) or (ccc2.value == None) :   # Пустая строка
                #print( 'Пустая строка. i=',i, impValues )
                continue
            else:  # Обычная строка
                impValues['подгруппа'] = subgrp
                impValues['группа_'] = grp
                for outColName in out_template.keys():
                    shablon = out_template[outColName]
                    for key in impValues.keys():
                        if shablon.find(key) >= 0:
                            shablon = shablon.replace(key, impValues[key])
                    if (outColName == 'закупка') and ('*' in shablon):
                        p = shablon.find("*")
                        vvv1 = float(shablon[:p])
                        vvv2 = float(shablon[p + 1:])
                        shablon = str(round(vvv1 * vvv2, 2))

                    recOut[outColName] = shablon.strip()
            '''
            if   'RUR'==recOut['валюта'] :
                       csvWriterRUR.writerow(recOut)
            elif 'USD'==recOut['валюта'] :
                       csvWriterUSD.writerow(recOut)    
            elif 'EUR'==recOut['валюта'] :
                       csvWriterEUR.writerow(recOut)    
            '''
            csvWriterUSD.writerow(recOut)

        except Exception as e:
            print(e)
            if str(e) == "'NoneType' object has no attribute 'rgb'":
                pass
            else:
                log.debug('Exception: <' + str(e) + '> при обработке строки ' +
                          str(i) + '.')

    log.info('Обработано ' + str(i_last) + ' строк.')
    #outFileRUR.close()
    #outFileEUR.close()
    outFileUSD.close()
예제 #3
0
def convert_excel2csv(cfg):
    csvFNameRUR  = cfg.get('basic','filename_out_RUR')
    csvFNameEUR  = cfg.get('basic','filename_out_EUR')
    csvFNameUSD  = cfg.get('basic','filename_out_USD')
    csvFNameRUR1 = 'csv_digis_RUR1.csv'
    csvFNameEUR1 = 'csv_digis_EUR1.csv'
    csvFNameUSD1 = 'csv_digis_USD1.csv'
    csvFNameRUR2 = 'csv_digis_RUR2.csv'
    csvFNameEUR2 = 'csv_digis_EUR2.csv'
    csvFNameUSD2 = 'csv_digis_USD2.csv'

    priceFName= cfg.get('basic','filename_in')
    sheetName = cfg.get('basic','sheetname')
    
    log.debug('Reading file ' + priceFName )
    sheet = sheetByName(fileName = priceFName, sheetName = sheetName)
    if not sheet :
        log.error("Нет листа "+sheetName+" в файле "+ priceFName)
        return False
    log.debug("Sheet   "+sheetName)
    out_cols = cfg.options("cols_out")
    in_cols  = cfg.options("cols_in")
    out_template = {}
    for vName in out_cols :
         out_template[vName] = cfg.get("cols_out", vName)
    in_cols_j = {}
    for vName in in_cols :
         in_cols_j[vName] = cfg.getint("cols_in",  vName)
    #brands,   discount     = config_read(cfgFName, 'discount')
    #for k in discount.keys():
    #    discount[k] = (100 - int(discount[k]))/100
    #print(discount)

    outFileRUR1 = open( csvFNameRUR1, 'w', newline='', encoding='CP1251', errors='replace')
    outFileRUR2 = open( csvFNameRUR2, 'w', newline='', encoding='CP1251', errors='replace')
    outFileUSD1 = open( csvFNameUSD1, 'w', newline='', encoding='CP1251', errors='replace')
    outFileUSD2 = open( csvFNameUSD2, 'w', newline='', encoding='CP1251', errors='replace')
    outFileEUR1 = open( csvFNameEUR1, 'w', newline='', encoding='CP1251', errors='replace')
    outFileEUR2 = open( csvFNameEUR2, 'w', newline='', encoding='CP1251', errors='replace')
    csvWriterRUR1 = csv.DictWriter(outFileRUR1, fieldnames=out_cols )
    csvWriterRUR2 = csv.DictWriter(outFileRUR2, fieldnames=out_cols )
    csvWriterEUR1 = csv.DictWriter(outFileEUR1, fieldnames=out_cols )
    csvWriterEUR2 = csv.DictWriter(outFileEUR2, fieldnames=out_cols )
    csvWriterUSD1 = csv.DictWriter(outFileUSD1, fieldnames=out_cols )
    csvWriterUSD2 = csv.DictWriter(outFileUSD2, fieldnames=out_cols )
    csvWriterRUR1.writeheader()
    csvWriterRUR2.writeheader()
    csvWriterEUR1.writeheader()
    csvWriterEUR2.writeheader()
    csvWriterUSD1.writeheader()
    csvWriterUSD2.writeheader()

    '''                                     # Блок проверки свойств для распознавания групп      XLSX                                  
    for i in range(2393, 2397):                                                         
        i_last = i
        ccc = sheet.cell( row=i, column=in_cols_j['группа'] )
        print(i, ccc.value)
        print(ccc.font.name, ccc.font.sz, ccc.font.b, ccc.font.i, ccc.font.color.rgb, '------', ccc.fill.fgColor.rgb)
        print('------')
    '''
    '''                                     # Блок проверки свойств для распознавания групп      XLS                                  
    for i in range(0, 75):                                                         
        xfx = sheet.cell_xf_index(i, 0)
        xf  = book.xf_list[xfx]
        bgci  = xf.background.pattern_colour_index
        fonti = xf.font_index
        ccc = sheet.cell(i, 0)
        if ccc.value == None :
            print (i, colSGrp, 'Пусто!!!')
            continue
                                         # Атрибуты шрифта для настройки конфига
        font = book.font_list[fonti]
        print( '---------------------- Строка', i, '-----------------------', sheet.cell(i, 0).value)
        print( 'background_colour_index=',bgci)
        print( 'fonti=', fonti, '           xf.alignment.indent_level=', xf.alignment.indent_level)
        print( 'bold=', font.bold)
        print( 'weight=', font.weight)
        print( 'height=', font.height)
        print( 'italic=', font.italic)
        print( 'colour_index=', font.colour_index )
        print( 'name=', font.name)
    return
    '''

    recOut  ={}
#   for i in range(1, sheet.nrows) :                                     # xls
    for i in range(1, sheet.max_row +1):                                 # xlsx
        i_last = i
        try:
            impValues = getXlsxString(sheet, i, in_cols_j)
            #impValues = getXlsString(sheet, i, in_cols_j)
            #print( impValues['закупка'])
            if impValues['закупка']=='0': # (ccc.value == None) or (ccc2.value == None) :    # Пустая строка
                pass
            else:                                                        # Обычная строка
                if impValues['закупка'] == '0.1':
                    impValues['валюта1'] = 'USD'
                if impValues['продажа'] == '0.1':
                    impValues['валюта2'] = 'USD'

                for outColName in out_template.keys() :
                    shablon = out_template[outColName]
                    for key in impValues.keys():
                        if shablon.find(key) >= 0 :
                            shablon = shablon.replace(key, impValues[key])
                    if (outColName == 'закупка') and ('*' in shablon) :
                        vvvv = float( shablon[ :shablon.find('*')     ] )
                        shablon = str( float(vvvv) * brand_koeft )
                    recOut[outColName] = shablon

                if recOut['валюта1']=='USD':
                    csvWriterUSD1.writerow(recOut)
                elif recOut['валюта1']=='EUR':
                    csvWriterEUR1.writerow(recOut)
                elif recOut['валюта1']=='руб.':
                    csvWriterRUR1.writerow(recOut)
                else :
                    log.error('Не распознана валюта1 "%s" ')

                if recOut['валюта2']=='USD':
                    csvWriterUSD2.writerow(recOut)
                elif recOut['валюта2']=='EUR':
                    csvWriterEUR2.writerow(recOut)
                elif recOut['валюта2']=='руб.':
                    csvWriterRUR2.writerow(recOut)
                else :
                    log.error('Не распознана валюта2 "%s" ')

        except Exception as e:
            print(e)
            if str(e) == "'NoneType' object has no attribute 'rgb'":
                pass
            else:
                log.debug('Exception: <' + str(e) + '> при обработке строки ' + str(i) +'.' )

    log.info('Обработано ' +str(i_last)+ ' строк.')
    outFileRUR1.close()
    outFileUSD1.close()
    outFileEUR1.close()
    outFileRUR2.close()
    outFileUSD2.close()
    outFileEUR2.close()
예제 #4
0
def convert_excel2csv(cfg):
    csvFNameRUR = cfg.get('basic', 'filename_out_RUR')
    csvFNameUSD = cfg.get('basic', 'filename_out_USD')
    priceFName = cfg.get('basic', 'filename_in')
    sheetName = cfg.get('basic', 'sheetname')

    log.debug('Reading file ' + priceFName)
    sheet = sheetByName(fileName=priceFName, sheetName=sheetName)
    if not sheet:
        log.error("Нет листа " + sheetName + " в файле " + priceFName)
        return False
    log.debug("Sheet   " + sheetName)
    out_cols = cfg.options("cols_out")
    in_cols = cfg.options("cols_in")
    out_template = {}
    for vName in out_cols:
        out_template[vName] = cfg.get("cols_out", vName)
    in_cols_j = {}
    for vName in in_cols:
        in_cols_j[vName] = cfg.getint("cols_in", vName)
    #brands,   discount     = config_read(cfgFName, 'discount')
    #for k in discount.keys():
    #    discount[k] = (100 - int(discount[k]))/100
    #print(discount)

    outFileRUR = open(csvFNameRUR,
                      'w',
                      newline='',
                      encoding='CP1251',
                      errors='replace')
    outFileUSD = open(csvFNameUSD,
                      'w',
                      newline='',
                      encoding='CP1251',
                      errors='replace')
    csvWriterRUR = csv.DictWriter(outFileRUR, fieldnames=out_cols)
    csvWriterUSD = csv.DictWriter(outFileUSD, fieldnames=out_cols)
    csvWriterRUR.writeheader()
    csvWriterUSD.writeheader()
    '''                                     # Блок проверки свойств для распознавания групп      XLSX                                  
    for i in range(2393, 2397):                                                         
        i_last = i
        ccc = sheet.cell( row=i, column=in_cols_j['группа'] )
        print(i, ccc.value)
        print(ccc.font.name, ccc.font.sz, ccc.font.b, ccc.font.i, ccc.font.color.rgb, '------', ccc.fill.fgColor.rgb)
        print('------')
    '''
    '''                                     # Блок проверки свойств для распознавания групп      XLS                                  
    for i in range(0, 75):                                                         
        xfx = sheet.cell_xf_index(i, 0)
        xf  = book.xf_list[xfx]
        bgci  = xf.background.pattern_colour_index
        fonti = xf.font_index
        ccc = sheet.cell(i, 0)
        if ccc.value == None :
            print (i, colSGrp, 'Пусто!!!')
            continue
                                         # Атрибуты шрифта для настройки конфига
        font = book.font_list[fonti]
        print( '---------------------- Строка', i, '-----------------------', sheet.cell(i, 0).value)
        print( 'background_colour_index=',bgci)
        print( 'fonti=', fonti, '           xf.alignment.indent_level=', xf.alignment.indent_level)
        print( 'bold=', font.bold)
        print( 'weight=', font.weight)
        print( 'height=', font.height)
        print( 'italic=', font.italic)
        print( 'colour_index=', font.colour_index )
        print( 'name=', font.name)
    return
    '''

    recOut = {}
    for i in range(1, sheet.max_row + 1):  # xlsx
        #   for i in range(1, sheet.nrows) :                                     # xls
        i_last = i
        try:
            ccc = sheet.cell(row=i, column=in_cols_j['группа_'])
            if ccc.font.b == True:  # Подгруппа
                grpName = sheet.cell(row=i, column=in_cols_j['группа_']).value
                continue
            impValues = getXlsxString(sheet, i, in_cols_j)  # xlsx
            #impValues = getXlsString(sheet, i, in_cols_j)               # xls
            #print( impValues )
            if impValues['код_'] == '' or impValues[
                    'код_'] == 'Артикул':  # Пустая строка
                pass
                #print( 'Пустая строка. i=',i, impValues )
            else:  # Обычная строка
                impValues['группа_'] = grpName
                for outColName in out_template.keys():
                    shablon = out_template[outColName]
                    for key in impValues.keys():
                        if shablon.find(key) >= 0:
                            shablon = shablon.replace(key, impValues[key])
                    if (outColName == 'закупка') and ('+' in shablon):
                        p = shablon.find("+")
                        vvv1 = float(shablon[:p])
                        vvv2 = float(shablon[p + 1:])
                        shablon = str(round(vvv1 + vvv2, 2))
                    recOut[outColName] = shablon.strip()

                if float(impValues["цена_usd"]) > 0.0:
                    recOut["валюта"] = "USD"
                    csvWriterUSD.writerow(recOut)
                else:
                    recOut["валюта"] = "РУБ"
                    csvWriterRUR.writerow(recOut)

        except Exception as e:
            print(e)
            if str(e) == "'NoneType' object has no attribute 'rgb'":
                pass
            else:
                log.debug('Exception: <' + str(e) + '> при обработке строки ' +
                          str(i) + '.')

    log.info('Обработано ' + str(i_last) + ' строк.')
    outFileRUR.close()
    outFileUSD.close()
예제 #5
0
def convert2csv(cfg):
    csvFName = cfg.get('basic', 'filename_out')
    priceFName = cfg.get('basic', 'filename_in')
    sheetName = cfg.get('basic', 'sheetname')

    log.debug('Reading file ' + priceFName)
    sheet = sheetByName(fileName=priceFName, sheetName=sheetName)
    if not sheet:
        log.error("Нет листа " + sheetName + " в файле " + priceFName)
        return False
    log.debug("Sheet   " + sheetName)
    out_cols = cfg.options("cols_out")
    in_cols = cfg.options("cols_in")
    out_template = {}
    for vName in out_cols:
        out_template[vName] = cfg.get("cols_out", vName)
    in_cols_j = {}
    for vName in in_cols:
        in_cols_j[vName] = cfg.getint("cols_in", vName)
    #brands,   discount     = config_read(cfgFName, 'discount')
    #for k in discount.keys():
    #    discount[k] = (100 - int(discount[k]))/100
    #print(discount)

    outFile = open(csvFName,
                   'w',
                   newline='',
                   encoding='CP1251',
                   errors='replace')
    csvWriter = csv.DictWriter(outFile, fieldnames=out_cols)
    csvWriter.writeheader()
    '''                                     # Блок проверки свойств для распознавания групп      XLSX                                  
    for i in range(2393, 2397):                                                         
        i_last = i
        ccc = sheet.cell( row=i, column=in_cols_j['группа'] )
        print(i, ccc.value)
        print(ccc.font.name, ccc.font.sz, ccc.font.b, ccc.font.i, ccc.font.color.rgb, '------', ccc.fill.fgColor.rgb)
        print('------')
    '''
    '''                                     # Блок проверки свойств для распознавания групп      XLS                                  
    for i in range(0, 75):                                                         
        xfx = sheet.cell_xf_index(i, 0)
        xf  = book.xf_list[xfx]
        bgci  = xf.background.pattern_colour_index
        fonti = xf.font_index
        ccc = sheet.cell(i, 0)
        if ccc.value == None :
            print (i, colSGrp, 'Пусто!!!')
            continue
                                         # Атрибуты шрифта для настройки конфига
        font = book.font_list[fonti]
        print( '---------------------- Строка', i, '-----------------------', sheet.cell(i, 0).value)
        print( 'background_colour_index=',bgci)
        print( 'fonti=', fonti, '           xf.alignment.indent_level=', xf.alignment.indent_level)
        print( 'bold=', font.bold)
        print( 'weight=', font.weight)
        print( 'height=', font.height)
        print( 'italic=', font.italic)
        print( 'colour_index=', font.colour_index )
        print( 'name=', font.name)
    return
    '''

    recOut = {}
    for i in range(1, sheet.nrows):  # xls
        #    for i in range(1, sheet.max_row +1) :                               # xlsx
        i_last = i
        try:
            '''
            xfx = sheet.cell_xf_index(i, 0)
            xf  = book.xf_list[xfx]
            level = xf.alignment.indent_level
            bgci  = xf.background.pattern_colour_index
            ccc   = sheet.cell(i, 0)
            value = ccc.value   
            '''
            #            impValues = getXlsxString(sheet, i, in_cols_j)
            impValues = getXlsString(sheet, i, in_cols_j)
            try:  # Пустое поле наследует значение из предыдущей строки.
                if impValues["grp1"] == "": impValues["grp1"] = grp1
                else: grp1 = impValues["grp1"]
            except Exception as e:
                pass
            for outColName in out_template.keys():
                shablon = out_template[outColName]
                for key in impValues.keys():
                    if shablon.find(key) >= 0:
                        shablon = shablon.replace(key, impValues[key])
                if (outColName in ("закупка", "продажа")) and ("*" in shablon):
                    p = shablon.find("*")
                    vvv1 = float(shablon[:p])
                    vvv2 = float(shablon[p + 1:])
                    shablon = str(round(vvv1 * vvv2, 2))
                recOut[outColName] = shablon.strip()

            if recOut['код'].lower() in ('', 'model', "артикул",
                                         "sku"):  # Пустая строка
                #print (i, 'Пустая строка!!!')
                continue
            csvWriter.writerow(recOut)

        except Exception as e:
            print(e)
            if str(e) == "'NoneType' object has no attribute 'rgb'":
                pass
            else:
                log.debug('Exception: <' + str(e) + '> при обработке строки ' +
                          str(i) + '.')

    log.info('Обработано ' + str(i_last) + ' строк.')
    outFile.close()
def convert_excel2csv(cfg, sklad_data):
    csvFName = cfg.get('basic', 'filename_out')
    priceFName = cfg.get('basic', 'filename_in')
    sheetName = cfg.get('basic', 'sheetname')

    log.debug('Reading file ' + priceFName)
    #    book = xlrd.open_workbook(priceFName.encode('cp1251'), formatting_info=True)
    #    sheet = sheetByName(fileName = priceFName, sheetName = sheetName)
    book, sheet = sheetByName(fileName=priceFName, sheetName=sheetName)

    if not sheet:
        log.error("Нет листа " + sheetName + " в файле " + priceFName)
        return False
    log.debug("Sheet   " + sheetName)
    out_cols = cfg.options("cols_out")
    in_cols = cfg.options("cols_in")
    out_template = {}
    for vName in out_cols:
        out_template[vName] = cfg.get("cols_out", vName)
    in_cols_j = {}
    for vName in in_cols:
        in_cols_j[vName] = cfg.getint("cols_in", vName)
    #brands,   discount     = config_read(cfgFName, 'discount')
    #for k in discount.keys():
    #    discount[k] = (100 - int(discount[k]))/100
    #print(discount)

    outFile = open(csvFName,
                   'w',
                   newline='',
                   encoding='CP1251',
                   errors='replace')
    csvWriter = csv.DictWriter(outFile, fieldnames=out_cols)
    csvWriter.writeheader()
    '''                                     # Блок проверки свойств для распознавания групп      XLSX                                  
    for i in range(2393, 2397):                                                         
        i_last = i
        ccc = sheet.cell( row=i, column=in_cols_j['группа'] )
        print(i, ccc.value)
        print(ccc.font.name, ccc.font.sz, ccc.font.b, ccc.font.i, ccc.font.color.rgb, '------', ccc.fill.fgColor.rgb)
        print('------')
    '''
    '''                                     # Блок проверки свойств для распознавания групп      XLS
    for i in range(1, 12):
        xfx = sheet.cell_xf_index(i, 1)
        book = xlrd.open_workbook(priceFName.encode('cp1251'), formatting_info=True)
        xf  = book.xf_list[xfx]
        bgci  = xf.background.pattern_colour_index
        fonti = xf.font_index
        ccc = sheet.cell(i, 1)
        if ccc.value == None :
            print (i, colSGrp, 'Пусто!!!')
            continue
                                         # Атрибуты шрифта для настройки конфига
        font = book.font_list[fonti]
        print( '---------------------- Строка', i, '-----------------------', sheet.cell(i, 1).value)
        print( 'background_colour_index=',bgci)
        print( 'fonti=', fonti, '           xf.alignment.indent_level=', xf.alignment.indent_level)
        print( 'bold=', font.bold)
        print( 'weight=', font.weight)
        print( 'height=', font.height)
        print( 'italic=', font.italic)
        print( 'colour_index=', font.colour_index )
        print( 'name=', font.name)
    return
    '''

    recOut = {}
    grp = ''
    subgrp = ''
    subgrp2 = ''
    #   for i in range(1, sheet.max_row +1) :                               # xlsx
    for i in range(1, sheet.nrows):  # xls
        i_last = i
        try:
            #impValues = getXlsxString(sheet, i, in_cols_j)              # xlsx
            impValues = getXlsString(sheet, i, in_cols_j)  # xls
            #print( impValues )
            xfx = sheet.cell_xf_index(i, 1)
            xf = book.xf_list[xfx]
            bgci = xf.background.pattern_colour_index
            fonti = xf.font_index

            if (impValues['код_'] in ('', 'Partnumber', 'Part No.')
                    or impValues['цена1']
                    in ('SRP, $', 'RRP, $', 'Цена MSRP')):  # Пустая строка
                continue
            if impValues[
                    'цена1'] == '0':  # Вместо отсутствия цены ставим цену 0.1
                impValues['цена1'] = '0.1'
            if cfg.has_option(
                    'cols_in', 'примечание'
            ) and impValues['примечание'] != '':  # Примечание
                impValues['примечание'] = ' / (' + impValues[
                    'примечание'] + ')'  # обрамляем скобками
            if "\n" in impValues['код_']:  # В многострочном коде берем
                p = impValues['код_'].rfind("\n")  # последнюю строку
                impValues['код_'] = impValues['код_'][p + 1:]

            if cfg.has_option(
                    'cols_in', 'подгруппа'
            ) and impValues['код_'] == '' and impValues['подгруппа'] != '':
                subgrp = impValues['подгруппа']  # Подгруппа
                continue
            elif bgci == 43:  # Подгруппа желтая
                subgrp2 = impValues['группа_']
                continue
            elif bgci == 22:  # Группа
                subgrp = ''
                grp = impValues['группа_']
            else:  # Обычная строка
                if cfg.has_option('cols_in', 'группа_'):
                    impValues['группа_'] = grp
                if cfg.has_option('cols_in', 'подгруппа'):
                    impValues['подгруппа'] = subgrp
                for outColName in out_template.keys():
                    shablon = out_template[outColName]
                    for key in impValues.keys():
                        if shablon.find(key) >= 0:
                            shablon = shablon.replace(key, impValues[key])
                    if (outColName == 'закупка') and ('*' in shablon):
                        if impValues['цена1'] == '0.1':
                            shablon = '0.1'
                        else:
                            p = shablon.find("*")
                            vvv1 = float(shablon[:p])
                            vvv2 = float(shablon[p + 1:])
                            shablon = str(round(vvv1 * vvv2, 2))

                    recOut[outColName] = shablon.strip()

                try:
                    recOut['наличие'] = sklad_data[impValues['код_']]
                except Exception as e:
                    recOut['наличие'] = ''
                csvWriter.writerow(recOut)

        except Exception as e:
            print(e)
            if str(e) == "'NoneType' object has no attribute 'rgb'":
                pass
            else:
                log.debug('Exception: <' + str(e) + '> при обработке строки ' +
                          str(i) + '.')

    log.info('Обработано ' + str(i_last) + ' строк.')
    outFile.close()
예제 #7
0
def convert_excel2csv(cfg):
    csvFName  = cfg.get('basic','filename_out')
    priceFName= cfg.get('basic','filename_in')
    sheetName = cfg.get('basic','sheetname')
    
    log.debug('Reading file ' + priceFName )
    sheet = sheetByName(fileName = priceFName, sheetName = sheetName)
    if not sheet :
        log.error("Нет листа "+sheetName+" в файле "+ priceFName)
        return False
    log.debug("Sheet   "+sheetName)
    out_cols = cfg.options("cols_out")
    in_cols  = cfg.options("cols_in")
    out_template = {}
    for vName in out_cols :
         out_template[vName] = cfg.get("cols_out", vName)
    in_cols_j = {}
    for vName in in_cols :
         in_cols_j[vName] = cfg.getint("cols_in",  vName)

    csvFNameRUR =csvFName[:-4]+'_RUR'+csvFName[-4:]
    csvFNameEUR =csvFName[:-4]+'_EUR'+csvFName[-4:]
    csvFNameUSD =csvFName[:-4]+'_USD'+csvFName[-4:]
    outFileRUR = open( csvFNameRUR, 'w', newline='', encoding='CP1251', errors='replace')
    outFileEUR = open( csvFNameEUR, 'w', newline='', encoding='CP1251', errors='replace')
    outFileUSD = open( csvFNameUSD, 'w', newline='', encoding='CP1251', errors='replace')
    csvWriterRUR = csv.DictWriter(outFileRUR, fieldnames=out_cols )
    csvWriterEUR = csv.DictWriter(outFileEUR, fieldnames=out_cols )
    csvWriterUSD = csv.DictWriter(outFileUSD, fieldnames=out_cols )
    csvWriterRUR.writeheader()
    csvWriterEUR.writeheader()
    csvWriterUSD.writeheader()

    recOut  ={}
    grpName = ''
    subGrpName = ''
    for i in range(2, sheet.max_row +1) :                                # xlsx
        i_last = i
        try:
            impValues = getXlsxString(sheet, i, in_cols_j)               # xlsx
            if sheet.cell( row=i, column=in_cols_j['группа_']).font.sz==16:     # группа
                grpName =  impValues['группа_']
                subGrpName = ''
                print(grpName)
                continue
            if sheet.cell( row=i, column=in_cols_j['подгруппа']).font.sz==12:   # подгруппа
                subGrpName = impValues['подгруппа']
                continue
            if impValues['код_']=='' or sheet.cell( row=i, column=in_cols_j['код_']).font.bold==True :   # Пустая строка
                #print( 'Пустая строка. i=',i, impValues )
                continue
            else :                                                              # Обычная строка
                impValues['группа_'] = grpName
                impValues['подгруппа'] = subGrpName
                for outColName in out_template.keys() :
                    shablon = out_template[outColName]
                    for key in impValues.keys():
                        if shablon.find(key) >= 0 :
                            shablon = shablon.replace(key, impValues[key])
                    if (outColName == 'закупка') and ('*' in shablon) :
                        p = shablon.find("*")
                        vvv1 = float(shablon[:p])
                        vvv2 = float(shablon[p+1:])
                        shablon = str(round(vvv1 * vvv2, 2))
                    recOut[outColName] = shablon.strip()

            #if   'RUR'==recOut['валюта'] :
            #           csvWriterRUR.writerow(recOut)
            #elif 'USD'==recOut['валюта'] :
            #           csvWriterUSD.writerow(recOut)    
            #elif 'EUR'==recOut['валюта'] :
            csvWriterEUR.writerow(recOut)    
            
        except Exception as e:
            print(e)
            if str(e) == "'NoneType' object has no attribute 'rgb'":
                pass
            else:
                log.debug('Exception: <' + str(e) + '> при обработке строки ' + str(i) +'.' )

    log.info('Обработано ' +str(i_last)+ ' строк.')
    outFileRUR.close()
    outFileUSD.close()
예제 #8
0
def convert_excel2csv(cfg):
    csvFfileNameRUR = cfg.get('basic', 'filename_out_RUR')
    csvFfileNameUSD = cfg.get('basic', 'filename_out_USD')
    priceFName = cfg.get('basic', 'filename_in')
    sheetName = cfg.get('basic', 'sheetname')

    outFileRUR = open(csvFfileNameRUR, 'w', newline='')
    outFileUSD = open(csvFfileNameUSD, 'w', newline='')

    log.debug('Reading file ' + priceFName)
    book, sheet = sheetByName(fileName=priceFName, sheetName=sheetName)
    if not sheet:
        log.error("Нет листа " + sheetName + " в файле " + priceFName)
        return False
    log.debug("Sheet   " + sheetName)
    out_cols = cfg.options("cols_out")
    in_cols = cfg.options("cols_in")
    out_template = {}
    for vName in out_cols:
        out_template[vName] = cfg.get("cols_out", vName)
    in_cols_j = {}
    for vName in in_cols:
        in_cols_j[vName] = cfg.getint("cols_in", vName)
    #brands,   discount     = config_read(cfgFName, 'discount')
    #for k in discount.keys():
    #    discount[k] = (100 - int(discount[k]))/100
    #print(discount)

    csvWriterRUR = csv.DictWriter(outFileRUR,
                                  fieldnames=cfg.options('cols_out'))
    csvWriterUSD = csv.DictWriter(outFileUSD,
                                  fieldnames=cfg.options('cols_out'))
    csvWriterRUR.writeheader()
    csvWriterUSD.writeheader()
    '''                                     # Блок проверки свойств для распознавания групп      XLSX
    for i in range(2, 28):
        i_last = i
        ccc = sheet.cell( row=i, column=in_cols_j['подгруппа'] )
        print(i, ccc.value)
        print(ccc.font.name, ccc.font.sz, ccc.font.b, ccc.font.i, '------', ccc.font.color.rgb, ccc.fill.bgColor.rgb, ccc.fill.fgColor.rgb)
        print('------')
    return
    '''
    '''                                     # Блок проверки свойств для распознавания групп      XLS                                  
    for i in range(19, 25):                                                         
        xfx = sheet.cell_xf_index(i, 1)
        xf  = book.xf_list[xfx]
        bgci  = xf.background.pattern_colour_index
        fonti = xf.font_index
        ccc = sheet.cell(i, 1)
        if ccc.value == None :
            print (i, colSGrp, 'Пусто!!!')
            continue
                                         # Атрибуты шрифта для настройки конфига
        font = book.font_list[fonti]
        print( '---------------------- Строка', i, '-----------------------', sheet.cell(i, 1).value)
        print( 'background_colour_index=',bgci)
        print( 'fonti=', fonti, '           xf.alignment.indent_level=', xf.alignment.indent_level)
        print( 'bold=', font.bold)
        print( 'weight=', font.weight)
        print( 'height=', font.height)
        print( 'italic=', font.italic)
        print( 'colour_index=', font.colour_index )
        print( 'name=', font.name)
    return
    '''

    recOut = {}
    subgrp = ''
    for i in range(1, sheet.max_row + 1):  # xlsx
        #   for i in range(1, sheet.nrows) :                                     # xls
        i_last = i
        try:
            #            xfx = sheet.cell_xf_index(i, 1)                              # xls
            #            xf  = book.xf_list[xfx]                                      # xls
            #            bgci  = xf.background.pattern_colour_index                   # xls
            impValues = getXlsxString(sheet, i, in_cols_j)  # xlsx
            #impValues = getXlsString(sheet, i, in_cols_j)                # xls
            #print( impValues )
            ccc1 = sheet.cell(row=i, column=in_cols_j['цена1']).value
            ccc2 = sheet.cell(row=i, column=in_cols_j['цена2']).value

            if float(impValues['цена1']) + float(
                    impValues['цена2']) < 0.1:  # ненужная строка
                continue
            else:  # Обычная строка
                if impValues['столбец j'] != '':
                    impValues['столбец j'] = '/рез.:' + impValues['столбец j']
                if impValues['столбец l'] != '':
                    impValues[
                        'столбец l'] = '/транзит:' + impValues['столбец l']
                if 'р' in str(ccc1) + str(ccc2):
                    impValues['валюта'] = 'RUR'
                else:
                    impValues['валюта'] = 'USD'
                if float(impValues['цена2']) > .0 and float(
                        impValues['цена1']) < 0.1:
                    impValues['цена1'] = impValues['цена2']
                for outColName in out_template.keys():
                    shablon = out_template[outColName]
                    for key in impValues.keys():
                        if shablon.find(key) >= 0:
                            shablon = shablon.replace(key, impValues[key])
                    if (outColName == 'закупка') and ('*' in shablon):
                        p = shablon.find("*")
                        vvv1 = float(shablon[:p])
                        vvv2 = float(shablon[p + 1:])
                        shablon = str(round(vvv1 * vvv2, 2))
                    recOut[outColName] = shablon.strip()

                if recOut['валюта'] == 'RUR':
                    csvWriterRUR.writerow(recOut)
                elif recOut['валюта'] == 'USD':
                    csvWriterUSD.writerow(recOut)
                else:
                    log.error('нераспознана валюта "%s" для товара "%s"',
                              recOut['валюта'], recOut['код производителя'])

        except Exception as e:
            print(e)
            if str(e) == "'NoneType' object has no attribute 'rgb'":
                pass
            else:
                log.debug('Exception: <' + str(e) + '> при обработке строки ' +
                          str(i) + '.')

    log.info('Обработано ' + str(i_last) + ' строк.')
    outFileRUR.close()
    outFileUSD.close()
예제 #9
0
def convert_excel2csv(cfg):
    priceFName = cfg.get('basic', 'filename_in')
    sheetName = cfg.get('basic', 'sheetname')

    log.debug('Reading file ' + priceFName)
    book, sheet = sheetByName(fileName=priceFName, sheetName=sheetName)
    if not sheet:
        log.error("Нет листа " + sheetName + " в файле " + priceFName)
        return False
    log.debug("Sheet   " + sheetName)
    out_cols = cfg.options("cols_out")
    in_cols = cfg.options("cols_in")
    out_template = {}
    for vName in out_cols:
        out_template[vName] = cfg.get("cols_out", vName)
    in_cols_j = {}
    for vName in in_cols:
        in_cols_j[vName] = cfg.getint("cols_in", vName)
    #brands,   discount     = config_read(cfgFName, 'discount')
    #for k in discount.keys():
    #    discount[k] = (100 - int(discount[k]))/100
    #print(discount)

    outFileUSD = False
    outFileEUR = False
    outFileRUR = False
    if cfg.has_option('basic', 'filename_out_RUR'):
        csvFfileNameRUR = cfg.get('basic', 'filename_out_RUR')
        outFileRUR = open(csvFfileNameRUR, 'w', newline='')
        csvWriterRUR = csv.DictWriter(outFileRUR,
                                      fieldnames=cfg.options('cols_out'))
        csvWriterRUR.writeheader()
    if cfg.has_option('basic', 'filename_out_USD'):
        csvFfileNameUSD = cfg.get('basic', 'filename_out_USD')
        outFileUSD = open(csvFfileNameUSD, 'w', newline='')
        csvWriterUSD = csv.DictWriter(outFileUSD,
                                      fieldnames=cfg.options('cols_out'))
        csvWriterUSD.writeheader()
    if cfg.has_option('basic', 'filename_out_EUR'):
        csvFfileNameEUR = cfg.get('basic', 'filename_out_EUR')
        outFileEUR = open(csvFfileNameEUR, 'w', newline='')
        csvWriterEUR = csv.DictWriter(outFileEUR,
                                      fieldnames=cfg.options('cols_out'))
        csvWriterEUR.writeheader()
    '''                                     # Блок проверки свойств для распознавания групп      XLSX
    for i in range(1, 8):
        i_last = i
        ccc = sheet.cell( row=i, column=in_cols_j['подгруппа'] )
        print(i, sheet.cell(row=i, column=in_cols_j['подгруппа']).value, ccc.value)
        print(ccc.font.name, ccc.font.sz, ccc.font.b, ccc.font.i, '------', ccc.font.color.value, ccc.fill.bgColor.value, ccc.fill.fgColor.value)
        print('------')
    return
    '''
    '''                                     # Блок проверки свойств для распознавания групп      XLS                                  
    for i in range(19, 25):                                                         
        xfx = sheet.cell_xf_index(i, 1)
        xf  = book.xf_list[xfx]
        bgci  = xf.background.pattern_colour_index
        fonti = xf.font_index
        ccc = sheet.cell(i, 1)
        if ccc.value == None :
            print (i, colSGrp, 'Пусто!!!')
            continue
                                         # Атрибуты шрифта для настройки конфига
        font = book.font_list[fonti]
        print( '---------------------- Строка', i, '-----------------------', sheet.cell(i, 1).value)
        print( 'background_colour_index=',bgci)
        print( 'fonti=', fonti, '           xf.alignment.indent_level=', xf.alignment.indent_level)
        print( 'bold=', font.bold)
        print( 'weight=', font.weight)
        print( 'height=', font.height)
        print( 'italic=', font.italic)
        print( 'colour_index=', font.colour_index )
        print( 'name=', font.name)
    return
    '''

    recOut = {}
    subgrp = ''
    grp = ''
    series = ''
    for i in range(1, sheet.max_row + 1):  # xlsx
        #   for i in range(1, sheet.nrows) :                                     # xls
        i_last = i
        try:
            #            xfx = sheet.cell_xf_index(i, 1)                              # xls
            #            xf  = book.xf_list[xfx]                                      # xls
            #            bgci  = xf.background.pattern_colour_index                   # xls
            impValues = getXlsxString(sheet, i, in_cols_j)  # xlsx
            #impValues = getXlsString(sheet, i, in_cols_j)                # xls
            #print( impValues )
            ccc1 = sheet.cell(row=i, column=in_cols_j['код_']).value

            if (sheet.cell(row=i,
                           column=in_cols_j['группа_']).fill.fgColor.value ==
                    'FFFFFF00'):  # группа
                grp = impValues['группа_']
                continue
            elif (sheet.cell(row=i,
                             column=in_cols_j['подгруппа']).fill.fgColor.value
                  == 'FF00B050'):  # подгруппа
                subgrp = impValues['подгруппа']
                continue
            elif ((sheet.cell(row=i,
                              column=in_cols_j['серия']).fill.fgColor.value
                   == 'FF92D050')
                  and (sheet.cell(row=i, column=in_cols_j['цена1']).value
                       == None)):  # серия
                series = impValues['серия']
                continue
            elif (impValues['цена1'] == '0'):  # лишняя строка
                continue
            impValues['подгруппа'] = subgrp
            impValues['группа_'] = grp
            impValues['серия'] = series
            impValues['тип_экрана'] = impValues['тип_экрана'].encode(
                'cp1251', errors='replace').decode('cp1251')

            for outColName in out_template.keys():
                shablon = out_template[outColName]
                for key in impValues.keys():
                    if shablon.find(key) >= 0:
                        shablon = shablon.replace(key, impValues[key])
                if (outColName == 'закупка') and ('*' in shablon):
                    p = shablon.find("*")
                    vvv1 = float(shablon[:p])
                    vvv2 = float(shablon[p + 1:])
                    shablon = str(round(vvv1 * vvv2, 2))
                recOut[outColName] = shablon.strip()

            recOut['код'] = nameToId(recOut['код'])
            if subgrp.find('Шар') < 0:
                recOut['описание'] = recOut['описание'] + ' (цена за 1 кв. м.)'
            '''
            if  recOut['продажа'] == '0.1':
                recOut['валюта'] = 'USD'
                recOut['закупка'] = '0.1'
            '''
            if recOut['валюта'] == 'RUR':
                csvWriterRUR.writerow(recOut)
            elif recOut['валюта'] == 'USD':
                csvWriterUSD.writerow(recOut)
            elif recOut['валюта'] == 'EUR':
                csvWriterEUR.writerow(recOut)
            else:
                log.error('нераспознана валюта "%s" для товара "%s"',
                          recOut['валюта'], recOut['код производителя'])

        except Exception as e:
            print(e)
            if str(e) == "'NoneType' object has no attribute 'rgb'":
                pass
            else:
                log.debug('Exception: <' + str(e) + '> при обработке строки ' +
                          str(i) + '.')

    log.info('Обработано ' + str(i_last) + ' строк.')
    if outFileRUR:
        outFileRUR.close()
    if outFileUSD:
        outFileUSD.close()
    if outFileEUR:
        outFileEUR.close()
예제 #10
0
def convert_excel2csv(cfg):
    csvFName = cfg.get('basic', 'filename_out')
    priceFName = cfg.get('basic', 'filename_in')
    sheetName = cfg.get('basic', 'sheetname')

    log.debug('Reading file ' + priceFName)
    sheet = sheetByName(fileName=priceFName, sheetName=sheetName)
    if not sheet:
        log.error("Нет листа " + sheetName + " в файле " + priceFName)
        return False
    log.debug("Sheet   " + sheetName)
    out_cols = cfg.options("cols_out")
    in_cols = cfg.options("cols_in")
    out_template = {}
    for vName in out_cols:
        out_template[vName] = cfg.get("cols_out", vName)
    in_cols_j = {}
    for vName in in_cols:
        in_cols_j[vName] = cfg.getint("cols_in", vName)
    #brands,   discount     = config_read(cfgFName, 'discount')
    #for k in discount.keys():
    #    discount[k] = (100 - int(discount[k]))/100
    #print(discount)

    csvFNameRUR = csvFName[:-4] + 'RUR' + csvFName[-4:]
    csvFNameUSD = csvFName[:-4] + 'USD' + csvFName[-4:]
    outFileRUR = open(csvFNameRUR,
                      'w',
                      newline='',
                      encoding='CP1251',
                      errors='replace')
    outFileUSD = open(csvFNameUSD,
                      'w',
                      newline='',
                      encoding='CP1251',
                      errors='replace')
    csvWriterRUR = csv.DictWriter(outFileRUR, fieldnames=out_cols)
    csvWriterUSD = csv.DictWriter(outFileUSD, fieldnames=out_cols)
    csvWriterRUR.writeheader()
    csvWriterUSD.writeheader()
    '''                                     # Блок проверки свойств для распознавания групп      XLSX                                  
    for i in range(5, 44):                                                         
        i_last = i
        ccc = sheet.cell( row=i, column=in_cols_j['код_'] )
        print(i, ccc.value)
        print(ccc.fill.fgColor)
        print(ccc.fill.fgColor.type)
        #print(ccc.font.color)
        #print(ccc.font.name, ccc.font.sz, ccc.font.b, ccc.font.i, 'ccc.font.color.rgb', '------', ccc.fill.fgColor.indexed)
        #print('------')
    return
    '''
    '''                                     # Блок проверки свойств для распознавания групп      XLS                                  
    for i in range(0, 75):                                                         
        xfx = sheet.cell_xf_index(i, 0)
        xf  = book.xf_list[xfx]
        bgci  = xf.background.pattern_colour_index
        fonti = xf.font_index
        ccc = sheet.cell(i, 0)
        if ccc.value == None :
            print (i, colSGrp, 'Пусто!!!')
            continue
                                         # Атрибуты шрифта для настройки конфига
        font = book.font_list[fonti]
        print( '---------------------- Строка', i, '-----------------------', sheet.cell(i, 0).value)
        print( 'background_colour_index=',bgci)
        print( 'fonti=', fonti, '           xf.alignment.indent_level=', xf.alignment.indent_level)
        print( 'bold=', font.bold)
        print( 'weight=', font.weight)
        print( 'height=', font.height)
        print( 'italic=', font.italic)
        print( 'colour_index=', font.colour_index )
        print( 'name=', font.name)
    return
    '''

    subgrp = ''
    qty_blank_lines = 0
    recOut = {}
    for i in range(2, sheet.max_row + 1):  # xlsx
        #   for i in range(2, sheet.nrows) :                                     # xls
        i_last = i
        try:
            impValues = getXlsxString(sheet, i, in_cols_j)  # xlsx
            #impValues = getXlsString(sheet, i, in_cols_j)               # xls
            #print( impValues )
            if (impValues['описание'] == ''
                    and impValues['подгруппа'] != ''):  # подгруппа
                subgrp = impValues['подгруппа']
                continue
            elif impValues['описание'] == '':  # Пустая строка
                # print( 'Пустая строка. i=',i, impValues )
                qty_blank_lines += 1
                if qty_blank_lines > 4:
                    break
                subgrp = ''
                continue
            elif (impValues['код_'] == ''
                  or impValues['код_'] == 'Арт.'):  # Пустая строка
                print(i, 'Пусто!!!')
                subgrp = ''
                continue
            else:  # Обычная строка
                qty_blank_lines = 0
                impValues['подгруппа'] = subgrp
                for outColName in out_template.keys():
                    shablon = out_template[outColName]
                    for key in impValues.keys():
                        if shablon.find(key) >= 0:
                            shablon = shablon.replace(key, impValues[key])
                    if (outColName == 'закупка') and ('0' == shablon):
                        shablon = impValues['цена3']
                    recOut[outColName] = shablon.strip()

            try:
                if '$' in (sheet.cell(row=i, column=in_cols_j['цена1']).value):
                    # USD
                    csvWriterUSD.writerow(recOut)
                else:
                    csvWriterRUR.writerow(recOut)
            except Exception as e:
                csvWriterRUR.writerow(recOut)
        except Exception as e:
            print(e)
            if str(e) == "'NoneType' object has no attribute 'rgb'":
                pass
            else:
                log.debug('Exception: <' + str(e) + '> при обработке строки ' +
                          str(i) + '.')

    log.info('Обработано ' + str(i_last) + ' строк.')
    outFileRUR.close()
    outFileUSD.close()
예제 #11
0
def convert_excel2csv(cfg):
    priceFName= cfg.get('basic','filename_in')
    sheetName = cfg.get('basic','sheetname')


    log.debug('Reading file ' + priceFName )
    book, sheet = sheetByName(fileName = priceFName, sheetName = sheetName)
    if not sheet:
        log.error("Нет листа "+sheetName+" в файле "+ priceFName)
        return False
    log.debug("Sheet   "+sheetName)
    out_cols = cfg.options("cols_out")
    in_cols  = cfg.options("cols_in")
    out_template = {}
    for vName in out_cols :
         out_template[vName] = cfg.get("cols_out", vName)
    in_cols_j = {}
    for vName in in_cols :
         in_cols_j[vName] = cfg.getint("cols_in",  vName)
    #brands,   discount     = config_read(cfgFName, 'discount')
    #for k in discount.keys():
    #    discount[k] = (100 - int(discount[k]))/100
    #print(discount)

    outFileUSD = False
    outFileEUR = False
    outFileRUR = False
    if cfg.has_option('basic','filename_out_RUR'):
        csvFfileNameRUR = cfg.get('basic', 'filename_out_RUR')
        outFileRUR = open(csvFfileNameRUR, 'w', newline='')
        csvWriterRUR = csv.DictWriter(outFileRUR, fieldnames=cfg.options('cols_out'))
        csvWriterRUR.writeheader()
    if cfg.has_option('basic', 'filename_out_USD'):
        csvFfileNameUSD = cfg.get('basic', 'filename_out_USD')
        outFileUSD = open(csvFfileNameUSD, 'w', newline='')
        csvWriterUSD = csv.DictWriter(outFileUSD, fieldnames=cfg.options('cols_out'))
        csvWriterUSD.writeheader()
    if cfg.has_option('basic', 'filename_out_EUR'):
        csvFfileNameEUR = cfg.get('basic', 'filename_out_EUR')
        outFileEUR = open(csvFfileNameEUR, 'w', newline='')
        csvWriterEUR = csv.DictWriter(outFileEUR, fieldnames=cfg.options('cols_out'))
        csvWriterEUR.writeheader()


    '''                                     # Блок проверки свойств для распознавания групп      XLSX
    for i in range(2, 15):
        i_last = i
        ccc = sheet.cell( row=i, column=in_cols_j['подгруппа'] )
        print(i, sheet.cell(row=i, column=in_cols_j['цена1']).value, ccc.value)
        print(ccc.font.name, ccc.font.sz, ccc.font.b, ccc.font.i, '------', 'ccc.font.color.rgb', ccc.fill.bgColor.rgb, 'ccc.fill.fgColor.rgb')
        print('------')
    return
    '''
    '''                                     # Блок проверки свойств для распознавания групп      XLS                                  
    for i in range(19, 25):                                                         
        xfx = sheet.cell_xf_index(i, 1)
        xf  = book.xf_list[xfx]
        bgci  = xf.background.pattern_colour_index
        fonti = xf.font_index
        ccc = sheet.cell(i, 1)
        if ccc.value == None :
            print (i, colSGrp, 'Пусто!!!')
            continue
                                         # Атрибуты шрифта для настройки конфига
        font = book.font_list[fonti]
        print( '---------------------- Строка', i, '-----------------------', sheet.cell(i, 1).value)
        print( 'background_colour_index=',bgci)
        print( 'fonti=', fonti, '           xf.alignment.indent_level=', xf.alignment.indent_level)
        print( 'bold=', font.bold)
        print( 'weight=', font.weight)
        print( 'height=', font.height)
        print( 'italic=', font.italic)
        print( 'colour_index=', font.colour_index )
        print( 'name=', font.name)
    return
    '''

    recOut  ={}
    subgrp = ''
    grp = ''
    for i in range(1, sheet.max_row +1) :                               # xlsx
#   for i in range(1, sheet.nrows) :                                     # xls
        i_last = i
        try:
#            xfx = sheet.cell_xf_index(i, 1)                              # xls
#            xf  = book.xf_list[xfx]                                      # xls
#            bgci  = xf.background.pattern_colour_index                   # xls
            impValues = getXlsxString(sheet, i, in_cols_j)                # xlsx
            #impValues = getXlsString(sheet, i, in_cols_j)                # xls
            #print( impValues )
            ccc1 = sheet.cell(row=i, column=in_cols_j['цена1']).value

            if sheetName == 'Antall':
                if (sheet.cell(row=i, column=in_cols_j['подгруппа']).font.b is True and
                    sheet.cell(row=i, column=in_cols_j['цена1']).value is None):          # подгруппа
                    subgrp = impValues['подгруппа']
                    continue
                elif (impValues['код_'] == '' or
                    impValues['код_'] == 'Модель' or
                    impValues['цена1'] == '0'):                                           # лишняя строка
                    continue
                impValues['подгруппа'] = subgrp

            elif sheetName == 'ArthurHolm':
                if (sheet.cell(row=i, column=in_cols_j['подгруппа']).font.b is True and
                    sheet.cell(row=i, column=in_cols_j['цена1']).value is None):          # подгруппа
                    subgrp = impValues['подгруппа']
                    continue
                elif (impValues['код_'] == '' or
                    impValues['код_'] == 'Модель' or
                    impValues['цена1'] == '0'):                                           # лишняя строка
                    continue
                impValues['подгруппа'] = subgrp
                impValues['описание'] = impValues['описание'].encode('cp1251', errors='replace').decode('cp1251')
                if '\n' in impValues['код_']:
                    p = impValues['код_'].find('\n')
                    impValues['код_'] = impValues['код_'][:p]

            elif sheetName == 'Aten':
                if (sheet.cell(row=i, column=in_cols_j['группа_']).font.b is True and
                    sheet.cell(row=i, column=in_cols_j['цена1']).value is None):          # группа
                    grp = impValues['группа_']
                    continue
                elif (impValues['код_'] == '' or
                    impValues['код_'] == 'Артикул' or
                    impValues['цена1'] == '0'):                                           # лишняя строка
                    continue
                impValues['группа_'] = grp
                if impValues['примечание'] != '':
                    impValues['примечание'] = ' (' + impValues['примечание'] + ')'

            elif sheetName == 'Biamp':
                if (sheet.cell(row=i, column=in_cols_j['группа_']).font.b is True and
                    sheet.cell(row=i, column=in_cols_j['цена1']).value is None and
                    sheet.cell(row=i, column=in_cols_j['группа_']).font.sz == 11.0):        # группа
                    grp = impValues['группа_'].encode('cp1251', errors='replace').decode('cp1251')
                    subgrp = ''
                    continue
                elif (sheet.cell(row=i, column=in_cols_j['подгруппа']).font.b is True and
                    sheet.cell(row=i, column=in_cols_j['цена1']).value is None and
                    sheet.cell(row=i, column=in_cols_j['подгруппа']).font.sz == 10.0):      # подгруппа
                    subgrp = impValues['подгруппа']
                    continue
                elif (impValues['код_'] == '' or
                    impValues['код_'] == 'Модель' or
                    impValues['цена1'] == '0'):                                             # лишняя строка
                    continue
                impValues['группа_'] = grp
                impValues['подгруппа'] = subgrp
                impValues['описание'] = impValues['описание'].encode('cp1251', errors='replace').decode('cp1251')
                impValues['код_'] = impValues['код_'].encode('cp1251', errors='replace').decode('cp1251')

            elif sheetName == 'B-Tech':
                if (impValues['код_'] == '' or
                    impValues['цена1'] == '0'):                                             # лишняя строка
                    continue

            elif sheetName == 'Maxell-Hitachi':
                if (sheet.cell(row=i, column=in_cols_j['подгруппа']).value is not None and
                    sheet.cell(row=i, column=in_cols_j['цена1']).value is None and
                    sheet.cell(row=i, column=in_cols_j['код_']).value is None):            # подгруппа
                    subgrp = impValues['подгруппа']
                    continue
                elif (impValues['код_'] == '' or
                    impValues['код_'] == 'Модель' or
                    impValues['яркость_'] == '' or
                    impValues['цена1'] == '0'):                                             # лишняя строка
                    continue
                impValues['подгруппа'] = subgrp
                if impValues['бренд'] == '':
                    impValues['бренд'] = 'Hitachi'
                if '\n' in impValues['код_']:
                    p = impValues['код_'].find('\n')
                    impValues['код_'] = impValues['код_'][:p]

            elif sheetName == 'DigitalProjection':
                if (sheet.cell(row=i, column=in_cols_j['группа_']).font.b is True and
                    sheet.cell(row=i, column=in_cols_j['код_']).value is None):            # группа
                    grp = impValues['группа_']
                    subgrp = ''
                    continue
                elif (impValues['код_'] == '' or
                    impValues['код_'] == 'Part #' or
                    impValues['цена1'] == '0'):                                             # лишняя строка
                    continue
                impValues['группа_'] = grp
                if impValues['3d'] != '':
                    impValues['3d'] = '3D'

            elif sheetName == 'Lumens':
                if (sheet.cell(row=i, column=in_cols_j['подгруппа']).value is not None and
                    sheet.cell(row=i, column=in_cols_j['цена1']).value is None and
                    sheet.cell(row=i, column=in_cols_j['код_']).value is None):             # подгруппа
                    subgrp = impValues['подгруппа']
                    continue
                elif (impValues['код_'] == '' or
                    impValues['код_'] == 'Модель' or
                    impValues['цена1'] == '0'):                                             # лишняя строка
                    continue
                impValues['подгруппа'] = subgrp
                impValues['описание'] = impValues['описание'].encode('cp1251', errors='replace').decode('cp1251')

            elif sheetName == 'Triolion':
                if (sheet.cell(row=i, column=in_cols_j['группа_']).value is not None and
                    sheet.cell(row=i, column=in_cols_j['цена1']).value is None):            # группа
                    grp = impValues['группа_']
                    continue
                elif (impValues['код_'] == '' or
                    impValues['код_'] == 'Модель' or
                    impValues['цена1'] == '0' or
                    grp.find('дисплеи') < 0):                                               # лишняя строка
                    continue
                impValues['группа_'] = grp
                impValues['описание'] = impValues['описание'].replace('×','x')
                impValues['описание'] = impValues['описание'].encode('cp1251', errors='replace').decode('cp1251')

            elif sheetName == 'Shure':
                if (impValues['код_'] == '' or
                    impValues['код_'] == 'Артикул' or
                    impValues['цена1'] == '0'):                                             # лишняя строка
                    continue
                if impValues['страна_'] != '':
                    impValues['страна_'] = 'Страна происхождения: ' + impValues['страна_']
                impValues['описание'] = impValues['описание'].encode('cp1251', errors='replace').decode('cp1251')

            elif sheetName == 'Sharp':
                if impValues['группа_'] != '':                                              # группа
                    grp = impValues['группа_']
                    continue
                elif (impValues['код_'] == '' or
                    impValues['код_'] == 'Модель' or
                    impValues['цена1'] == '0'):                                             # лишняя строка
                    continue
                if impValues['группа_'] == '':
                    impValues['группа_'] = grp

            elif sheetName == 'LG':
                if (sheet.cell(row=i, column=in_cols_j['группа_']).font.b is True and
                    sheet.cell(row=i, column=in_cols_j['цена1']).value is None):            # группа
                    grp = impValues['группа_']
                    subgrp = ''
                    continue
                elif (sheet.cell(row=i, column=in_cols_j['подгруппа']).font.b is True and
                    sheet.cell(row=i, column=in_cols_j['цена1']).value is not None):        # подгруппа
                    subgrp = impValues['подгруппа']
                elif (impValues['код_'] == '' or
                    impValues['код_'] == 'Артикул' or
                    impValues['цена1'] == '0'):                                             # лишняя строка
                    continue
                impValues['группа_'] = grp
                impValues['подгруппа'] = subgrp

            elif sheetName == 'Yamaha':
                if (impValues['код_'] == '' or
                    impValues['код_'] == 'Модель' or
                    impValues['цена1'] == '0'):                                             # лишняя строка
                    continue
                if impValues['страна_'] != '':
                    impValues['страна_'] = 'Страна происхождения: ' + impValues['страна_']
                if impValues['статус'] != '':
                    impValues['статус'] = '(' + impValues['статус'] + ')'
                impValues['описание'] = impValues['описание'].encode('cp1251', errors='replace').decode('cp1251')

            else:
                log.error('нераспознан sheetName "%s"', sheetName)      # далее общая для всех обработка

            for outColName in out_template.keys():
                shablon = out_template[outColName]
                for key in impValues.keys():
                    if shablon.find(key) >= 0:
                        shablon = shablon.replace(key, impValues[key])
                if (outColName == 'закупка') and ('*' in shablon) :
                    p = shablon.find("*")
                    vvv1 = float(shablon[:p])
                    vvv2 = float(shablon[p+1:])
                    shablon = str(round(vvv1 * vvv2, 2))
                recOut[outColName] = shablon.strip()

            recOut['код'] = nameToId(recOut['код'])
            if  recOut['продажа'] == '0.1':
                recOut['валюта'] = 'USD'
                recOut['закупка'] = '0.1'
            if recOut['валюта'] == 'RUR':
                csvWriterRUR.writerow(recOut)
            elif recOut['валюта'] == 'USD':
                csvWriterUSD.writerow(recOut)
            elif recOut['валюта'] == 'EUR':
                csvWriterEUR.writerow(recOut)
            else:
                log.error('нераспознана валюта "%s" для товара "%s"', recOut['валюта'], recOut['код производителя'])

        except Exception as e:
            print(e)
            if str(e) == "'NoneType' object has no attribute 'rgb'":
                pass
            else:
                log.debug('Exception: <' + str(e) + '> при обработке строки ' + str(i) + '.')

    log.info('Обработано ' + str(i_last) + ' строк.')
    if outFileRUR:
        outFileRUR.close()
    if outFileUSD:
        outFileUSD.close()
    if outFileEUR:
        outFileEUR.close()