Example #1
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()
Example #2
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()