Ejemplo n.º 1
0
def set_cells_format(number_rows, worker):
    #Покраска зеленым
    print "Применение форматирования."
    worker.ReportProgress(94, u"Применение форматирования.")
    cell_properties = sdk.CellProperties()
    cell_properties.backgroundColor = sdk.ColorRGBA(146, 208, 80, 1)
    #cell_properties.verticalAlignment = sdk.VerticalAlignment_Center
    # Задаем диапозон B4:S - конечная строка
    # Применение форматирования B4:S - конечная строка
    worker.ReportProgress(95, u"Применение форматирования для диапозона B4:W"+ number_rows)
    cell_range = table_output_xlsx_11.getCellRange("B4:W" + number_rows)
    cell_range.setCellProperties(cell_properties)

    # Задаем вертикальное центрирование
    # для диапозона А4-А - конечная строка.
    worker.ReportProgress(96, u"Применение форматирования для диапозона А4:А" + number_rows)
    cell_properties_aligment = sdk.CellProperties()
    cell_properties_aligment.backgroundColor = sdk.ColorRGBA(0, 0, 0, 0)
    cell_properties_aligment.verticalAlignment = sdk.VerticalAlignment_Center
    cell_range_aligment = table_output_xlsx_11.getCellRange("A4:A" + number_rows)
    for c in cell_range_aligment:
        c.setCellProperties(cell_properties_aligment)
    #cell_range_aligment.setCellProperties(cell_properties_aligment) Баг-репорт

    # Формат Date для столбца E4
    worker.ReportProgress(97, u"Формат Date для столбца E4")
    cell_range_date = table_output_xlsx_11.getCellRange("F4:F" + number_rows)
    for c in cell_range_date:
        c.setFormat(sdk.CellFormat_Date)
Ejemplo n.º 2
0
def error_data(data_error, worker): # Раскрашивает в выходном файле строки с ошибками
    worker.ReportProgress(98, u"Помечаем ошибки")
    for i in data_error:
        cell_properties = sdk.CellProperties()
        cell_properties.backgroundColor = sdk.ColorRGBA(255, 0, 0, 1)
        cell_properties.verticalAlignment = sdk.VerticalAlignment_Center
        cell_range = table_output_xlsx_11.getCellRange("B" + str(i+3)+":W"+str(i+3))
        cell_range.setCellProperties(cell_properties)
Ejemplo n.º 3
0
def main__(worker, folderName,mydirs_):
    def message_lose(table, i):
        last_name = table.getCell("B" + str(i)).getFormattedValue()
        first_name = table.getCell("C" + str(i)).getFormattedValue()
        bookmarks_lose.getBookmarkRange('name').replaceText(last_name + ' ' + first_name)
        f_path = (mydirs_[1]+"\\"+'№'+ str(i - 3) + ' '+ last_name + ' ' + first_name+ ' ' +os.path.basename(mydirs_[5])).encode('utf-8')
        document_lose.saveAs((f_path))
    def message_win(table, i):
        last_name = table.getCell("B" + str(i)).getFormattedValue()
        first_name = table.getCell("C" + str(i)).getFormattedValue()
        bookmarks_win.getBookmarkRange('name').replaceText(last_name + ' ' + first_name)
        f_path = (mydirs_[1]+"\\"+'№'+ str(i - 3) + ' '+ last_name + ' ' + first_name+ ' ' +os.path.basename(mydirs_[6])).encode('utf-8')
        document_win.saveAs((f_path))
    def paper_win(table, i):
        last_name = table.getCell("B" + str(i)).getFormattedValue()
        first_name = table.getCell("C" + str(i)).getFormattedValue()
        middle_name = table.getCell("D" + str(i)).getFormattedValue()
        bookmarks_paper_win.getBookmarkRange('Last_name').replaceText(last_name)
        bookmarks_paper_win.getBookmarkRange('First_middle_name').replaceText(first_name + ' ' + middle_name)
        bookmarks_paper_win.getBookmarkRange('scores').replaceText('100')

        output_file =mydirs_[2]+"\\"+'№' +str(i - 3) + ' ' + last_name + ' ' + first_name + '.pdf'
        document_paper_win.exportAs(str(output_file), sdk.ExportFormat_PDFA1)


    input_xls = (folderName + "\\"+os.path.basename(mydirs_[3])).encode('utf-8')

    template_win_doc = mydirs_[6].encode('utf-8')
    template_lose_doc = mydirs_[5].encode('utf-8')
    template_paper_win_doc = mydirs_[4].encode('utf-8')
    application = sdk.Application()
    document_win = application.loadDocument(template_win_doc)
    bookmarks_win = document_win.getBookmarks()
    document_lose = application.loadDocument(template_lose_doc)
    bookmarks_lose = document_lose.getBookmarks()
    document_paper_win = application.loadDocument(template_paper_win_doc)
    bookmarks_paper_win = document_paper_win.getBookmarks()
    try:
        document_xls_intput = application.loadDocument(input_xls)
    except Exception:
        raise Exception('This is the exception you expect to handle')
    table = document_xls_intput.getBlocks().getTable(0)
    last_row = table.getRowsCount()
    k = 0
    for i in range(4, last_row + 1):
        k += 1
        percentage = int((k * 100) / (last_row - 3))
        worker.ReportProgress(percentage, u"Формирование грамот и писем.")
        if worker.CancellationPending == True:
            worker.ReportProgress(percentage, u"Отмена задания")
            time.sleep(1)
            return
        if table.getCell("AL" + str(i)).getFormattedValue() == 'да':
            message_win(table, i)
            paper_win(table, i)
        elif table.getCell("AL" + str(i)).getFormattedValue() == 'нет':
            message_lose(table, i)
Ejemplo n.º 4
0
def extract_txt_doc(path,folderName,mydirs_,i,lena):
    filename=os.path.basename(path)
    document_xls_input = application.loadDocument(path.encode('utf-8'))
    table_input = document_xls_input.getBlocks().getTable(0)

    last_name = table_input.getCell('C6').getRawValue()
    first_name = table_input.getCell('C8').getRawValue()
    middle_name = table_input.getCell('C10').getRawValue()

    date_birth = table_input.getCell('C12').getFormattedValue()
    country = table_input.getCell('C14').getRawValue()
    district = table_input.getCell('C15').getRawValue()
    post_index = table_input.getCell('C16').getRawValue()
    region = table_input.getCell('C18').getRawValue()
    city = table_input.getCell('C20').getRawValue()
    #address = table_input.getCell('C22').getRawValue()
    school = table_input.getCell('C22').getRawValue()
    school_address = table_input.getCell('C24').getRawValue()
    exp = table_input.getCell('C26').getRawValue()
    cert_1 = table_input.getCell('C27').getRawValue()
    cert_2 = table_input.getCell('C28').getRawValue()
    cert_3 = table_input.getCell('C29').getRawValue()

    phone = table_input.getCell('C30').getRawValue()
    email = table_input.getCell('C32').getRawValue()

    parent_fio = table_input.getCell('C34').getRawValue()
    parent_email = table_input.getCell('C38').getRawValue()
    parent_phone = table_input.getCell('C40').getRawValue()
    parent_work = table_input.getCell('C42').getRawValue()


    #Раскрашиваем ячейки в анкетах с ошибками
    dict_cells = {
        'C6': last_name,
        'C8': first_name,
        'C10': middle_name,

        'C12': date_birth,
        'C14': country,
        'C15': district,
        'C16': post_index,
        'C18': region,
        'C20': city,
        'C22': school,
        'C24': school_address,
        'C26': exp,
        'C27': cert_1,
        'C28': cert_2,
        'C29': cert_3,

        'C30': phone,
        'C32': email,

        'C34': parent_fio,
        'C38': parent_email,
        'C40': parent_phone,
        'C42': parent_work,
    }
    cell_properties = table_input.getCell('C6').getCellProperties()
    cell_properties.backgroundColor = sdk.ColorRGBA(255, 0, 0, 1)
    is_changed = False
    is_first_error = True
    log = []
    for key, val in dict_cells.iteritems():
        if not val:
            # Помечаем ошибки красным цветом в входном файле
            table_input.getCell(key).setCellProperties(cell_properties)
            log = log_file(filename, key, is_first_error, log)
            is_changed = True
            is_first_error = False
    log_file_rec(log,folderName)

    if is_changed:
        #document_xls_input.saveAs((mydirs_[0]+"\\"+filename).encode('utf-8'))
        document_xls_input.saveAs((mydirs_[0] + "\\"+"№_"+str(lena + i)+"_"+last_name+"_"+first_name+"_Ошибка.xlsx").encode('utf-8'))
        os.remove(path)
    else:
        os.rename(path, os.path.dirname(path) + "\\"+"№_"+str(lena + i)+"_"+last_name+"_"+first_name+"_Обработан.xlsx")
    full_row_lst = [
                    last_name,
                    first_name,
                    middle_name,
                    date_birth,
                    country,
                    district,
                    post_index,
                    region,
                    city,
                    school,
                    school_address,
                    exp,
                    cert_1 + ", " + cert_2 + ", " +cert_3,
                    phone,
                    email,
                    parent_fio,
                    parent_email,
                    parent_phone,
                    parent_work]
    return full_row_lst
Ejemplo n.º 5
0
def main_(worker, folderName,mydirs_,date_end):
    global application
    application = sdk.Application()
    folder_url = mydirs_[6] #Анкеты
    for i in range(11, 15):
        globals()['output_file_url_xls_%d' % i] = mydirs_[i].encode('utf-8')                                #output path Сводный, Артек 1,2,3
        globals()['document_xls_%s' % i] = application.loadDocument(mydirs_[i].encode('utf-8'))             #load Сводный, Артек 1,2,3
        globals()['table_output_xlsx_%s' % i] = (globals()['document_xls_%s' % i]).getBlocks().getTable(0)  #table Сводный, Артек 1,2,3

    all_str_lst = []
    error_index = []
    lena=0
    regex_done = '№_\d+.*_Обработан\.xlsx'
    regex_not_prep = '(?<!_Обработан).xlsx'  # Попадание в список не обработанных, далее работаем только с ними.
    for root, dirs, files in os.walk(folder_url):
        del dirs[:] # go only one level deep
        filtered_done = [i for i in files if re.search(regex_done, str(i))]
        filtered_not_prep=[i for i in files  if re.search(regex_not_prep,str(i))]
    print "Количество файлов не обработанных: ", len(filtered_not_prep)
    if len(filtered_done+filtered_not_prep)==0:
        raise Exception(u"Нет необходимых xlsx файлов в папке анкеты")
    if len(filtered_not_prep)==0:
        print "Добавление записей не требуется!"
        worker.ReportProgress(100, u"Выполнено.")
        return
    else:
        i = 1
        if len(filtered_done)>0:
            lena = int((filtered_done[len(filtered_done) - 1]).split("_")[1])#№ последнего
            print "lena", lena
        for filename in filtered_not_prep:
            percentage = (filtered_not_prep.index(filename)*91)/len(filtered_not_prep)
            # print worker.WorkerReportsProgress
            # try:
            worker.ReportProgress(percentage, u"Экспорт анкет.")
            if worker.CancellationPending == True:
                worker.ReportProgress(percentage, u"Отмена задания")
                time.sleep(1)
                return
            # except Exception as e:
            #     print e.message
            path = root + "\\"+filename
            #path = path.encode('utf8')
            dict_str = extract_txt_doc(path,folderName,mydirs_,i,lena) #folderName - textboxBrowse.Text
            all_str_lst.append(dict_str)
            i += 1

    error_files_count = 0
    for i in range(0, len(all_str_lst)):   #от 0 до len записей
        p = len(error_index)
        for v in all_str_lst[i]:
            if not v:
                #all_str_lst.pop(i)
                error_index.append(i)
        if len(error_index) > p:
            error_files_count += 1
    index_del=set(error_index)
    for index in sorted(index_del, reverse=True):
        del all_str_lst[index]   #Удаление строк из списка в которых есть ошибка
    #clear_content()
    print "Количество записей с ошибками: ", len(error_index)
    print "Количество файлов с ошибками: ", error_files_count
    # Выделение строк в таблице по количеству строк из документов
    n_rows = table_output_xlsx_11.getRowsCount()
    rows_c = len(all_str_lst)
    #print "n_rows,rows_c= ", n_rows ,rows_c
    if rows_c>0:
        if table_output_xlsx_11.getCell("A4").getRawValue()=='':
            #Если пустая строка
            n_rows = n_rows-1
            rows_c=rows_c-1
            for i in range(11, 15):
                globals()['table_output_xlsx_%s' % i].insertRowAfter(n_rows, copyRowStyle=True, rowsCount=rows_c) #добавить в конец количство
        else:
            for i in range(11, 15):
                globals()['table_output_xlsx_%s' % i].insertRowAfter(n_rows-1, copyRowStyle=True, rowsCount=rows_c)  # добавить в конец количство
    number_rows = str(table_output_xlsx_11.getRowsCount())
    print "Количество строк в документе: ", number_rows
    # Записываем результат в таблицу
    #datetime1_end=convert_date(111)
    date_end=convert_time(date_end)
    write_table(all_str_lst, worker,date_end,n_rows+1)
    set_cells_format(number_rows, worker)
    write_formules(worker, table_output_xlsx_11.getRowsCount(),n_rows+1)
    #error_data(error_index, worker)
    worker.ReportProgress(99, u"Сохранение XLSX.")
    for i in range(11, 15):
        globals()['document_xls_%s' % i].saveAs(globals()['output_file_url_xls_%s' % i])
    #raise Exception('This is the exception you expect to handle') #Аналог Throw для обработки исключений
    worker.ReportProgress(100, u"Готово.")
Ejemplo n.º 6
0
def extract_txt_doc(filename, path, folderName):
    document_xls_input = application.loadDocument(path)
    table_input = document_xls_input.getBlocks().getTable(0)

    last_name = table_input.getCell('C6').getFormattedValue()
    first_name = table_input.getCell('C8').getFormattedValue()
    middle_name = table_input.getCell('C10').getFormattedValue()

    date_birth = table_input.getCell('C12').getFormattedValue()
    district = table_input.getCell('C14').getFormattedValue()
    post_index = table_input.getCell('C16').getFormattedValue()
    region = table_input.getCell('C18').getFormattedValue()
    city = table_input.getCell('C20').getFormattedValue()
    #address = table_input.getCell('C22').getFormattedValue()
    school = table_input.getCell('C22').getFormattedValue()
    school_address = table_input.getCell('C24').getFormattedValue()
    exp = table_input.getCell('C26').getFormattedValue()
    cert = table_input.getCell('C28').getFormattedValue()

    phone = table_input.getCell('C30').getFormattedValue()
    email = table_input.getCell('C32').getFormattedValue()

    parent_fio = table_input.getCell('C34').getFormattedValue()
    parent_email = table_input.getCell('C38').getFormattedValue()
    parent_phone = table_input.getCell('C40').getFormattedValue()
    parent_work = table_input.getCell('C42').getFormattedValue()

    #Раскрашиваем ячейки в анкетах с ошибками
    dict_cells = {
        'C6': last_name,
        'C8': first_name,
        'C10': middle_name,
        'C12': date_birth,
        'C14': district,
        'C16': post_index,
        'C18': region,
        'C20': city,
        'C22': school,
        'C24': school_address,
        'C26': exp,
        'C28': cert,
        'C30': phone,
        'C32': email,
        'C34': parent_fio,
        'C38': parent_email,
        'C40': parent_phone,
        'C42': parent_work,
    }
    cell_properties = table_input.getCell('C6').getCellProperties()
    cell_properties.backgroundColor = sdk.ColorRGBA(255, 0, 0, 1)
    is_changed = False
    is_first_error = True
    log = []
    for key, val in dict_cells.iteritems():
        if not val:
            # Помечаем ошибки красным цветом в входном файле
            table_input.getCell(key).setCellProperties(cell_properties)
            log = log_file(filename, key, is_first_error, log)
            is_changed = True
            is_first_error = False
    log_file_rec(log, folderName)

    if is_changed:
        document_xls_input.saveAs(
            (folderName + u"\\Ошибки\\" + filename).encode('utf-8'))

    full_row_lst = [
        last_name, first_name, middle_name, date_birth, district, post_index,
        region, city, school, school_address, exp, cert, phone, email,
        parent_fio, parent_phone, parent_email, parent_work
    ]
    return full_row_lst
Ejemplo n.º 7
0
def main_(s):
    global application
    application = sdk.Application()
    global document_xls
    folder_url = mydirs_[7]  #Анкеты
    input_file_url_xls = mydirs_[3].encode(
        'utf-8')  #input шаблон с рейтингования
    output_file_url_xls = mydirs_[11].encode(
        'utf-8')  #Output с размещением системы рейтингования
    for i in range(12, 15):
        globals()['output_file_url_xls_%d' %
                  (i - 4)] = mydirs_[i].encode('utf-8')
    document_xls = application.loadDocument(input_file_url_xls)
    document_xls_2 = application.loadDocument(mydirs_[8].encode('utf-8'))
    global table_output_xlsx, table_output_xlsx_2
    table_output_xlsx = document_xls.getBlocks().getTable(0)
    table_output_xlsx_2 = document_xls_2.getBlocks().getTable(0)
    all_str_lst = []
    error_index = []
    regex = compile('.*xlsx$')
    for root, dirs, files in os.walk(folder_url):
        del dirs[:]  # go only one level deep
        filtered = [i for i in files if regex.match(i)]
        print "Количество файлов: ", len(filtered)
        if not len(filtered):
            raise Exception(u"Нет необходимых xlsx файлов в папке анкеты")
        for filename in filtered:
            percentage = (filtered.index(filename) * 91) / len(filtered)
            # print worker.WorkerReportsProgress
            # try:
            worker.ReportProgress(percentage, u"Экспорт анкет.")
            if worker.CancellationPending == True:
                worker.ReportProgress(percentage, u"Отмена задания")
                time.sleep(1)
                return
            # except Exception as e:
            #     print e.message
            path = root + "\\" + filename
            path = path.encode('utf8')
            dict_str = extract_txt_doc(filename, path, folderName)
            all_str_lst.append(dict_str)

    all_str_sorted_lst = sorted(all_str_lst, key=lambda k: k[0])
    error_files_count = 0
    for i in range(0, len(all_str_sorted_lst)):  #от 0 до len записей
        p = len(error_index)
        """keys_arr = [0, 1, 2] # columns indexes
        for k in [0,1,2]:
            if not all_str_sorted_lst[i][k]:
                error_index.append(i+1)
                """
        for v in all_str_sorted_lst[i]:
            if not v:
                error_index.append(i + 1)
        if len(error_index) > p:
            error_files_count += 1
    clear_content()
    print "Количество записей с ошибками: ", len(error_index)
    print "Количество файлов с ошибками: ", error_files_count
    # Выделение строк в таблице по количеству строк из документов
    n_rows = len(all_str_sorted_lst) - table_output_xlsx.getRowsCount() + 3
    n_rows_2 = len(all_str_sorted_lst) - table_output_xlsx_2.getRowsCount() + 3
    # необходимое кол-во строк (+3, т.к. 3 строки в заголовке таблицы)
    if n_rows > 0:
        table_output_xlsx.insertRowAfter(2,
                                         copyRowStyle=True,
                                         rowsCount=n_rows)
        table_output_xlsx_2.insertRowAfter(3,
                                           copyRowStyle=True,
                                           rowsCount=n_rows_2)

    number_rows = str(table_output_xlsx.getRowsCount())
    print "Количество строк в документе: ", number_rows
    # Записываем результат в таблицу
    write_table(all_str_sorted_lst, worker)
    set_cells_format(number_rows, worker)
    error_data(error_index, worker)
    worker.ReportProgress(99, u"Сохранение XLSX.")
    document_xls.saveAs(output_file_url_xls)
    document_xls_2.saveAs(output_file_url_xls_8)
    table_output_xlsx_2.getCell("B1").setText("Жюри 2")
    document_xls_2.saveAs(output_file_url_xls_9)
    table_output_xlsx_2.getCell("B1").setText("Жюри 3")
    document_xls_2.saveAs(output_file_url_xls_10)
    #raise Exception('This is the exception you expect to handle') #Аналог Throw для обработки исключений
    worker.ReportProgress(100, u"Готово.")
Ejemplo n.º 8
0
def main_(worker, folderName,mydirs_,date_end):
    global application
    application = sdk.Application()
    folder_url = mydirs_[6] #Анкеты
    for i in range(11, 15):
        globals()['output_file_url_xls_%d' % i] = mydirs_[i].encode('utf-8')                                #output path Сводный, Артек 1,2,3
        globals()['document_xls_%s' % i] = application.loadDocument(mydirs_[i].encode('utf-8'))             #load Сводный, Артек 1,2,3
        globals()['table_output_xlsx_%s' % i] = (globals()['document_xls_%s' % i]).getBlocks().getTable(0)  #table Сводный, Артек 1,2,3

    all_str_lst = []
    error_index = []
    def split(s):
        for x, y in re.findall('(\d*)(\D*)', s):
            yield '', int(x or '0')
            yield y, 0
    def s(c):
        return list(split(c))

    regex_not_er = '(?<=_Ошибка).xlsx'
    regex_done = '№_\d+.*_Обработан\.xlsx'
    regex_not_prep = '(?<!_Обработан).xlsx'  # Попадание в список не обработанных, далее работаем только с ними.
    for root, dirs, files in os.walk(mydirs_[0]):
        del dirs[:]  # go only one level deep
        filtered_erorr = [i for i in files if re.search(regex_not_er, str(i))]
    for root, dirs, files in os.walk(folder_url):
        del dirs[:] # go only one level deep
        filtered_done = [i for i in files if re.search(regex_done, str(i))] #Обработанные
        filtered_not_prep=[i for i in files  if re.search(regex_not_prep,str(i))] #Не обработанные

    filtered_erorr = sorted(filtered_erorr, key=s, reverse=True)
    filtered_done = sorted(filtered_done, key=s)
    print "Количество файлов не обработанных: ", len(filtered_not_prep)
    if len(filtered_done+filtered_not_prep)==0:
        raise Exception(u"Нет необходимых xlsx файлов в папке анкеты")
    lena = 1
    if len(filtered_not_prep)==0:
        print "Добавление записей не требуется!"
        worker.ReportProgress(100, u"Выполнено.")
        return
    else:
        if len(filtered_done)>0:
            lena = int((filtered_done[len(filtered_done) - 1]).split("_")[1]) + 1  # № последнего
            if filtered_erorr:
                lena_ = int((filtered_erorr[0]).split("_")[1]) + 1
                if lena < lena_:
                    lena=lena_
        for filename in filtered_not_prep:
            percentage = (filtered_not_prep.index(filename)*91)/len(filtered_not_prep)
            # print worker.WorkerReportsProgress
            # try:
            worker.ReportProgress(percentage, u"Экспорт анкет.")
            if worker.CancellationPending == True:
                worker.ReportProgress(percentage, u"Отмена задания")
                time.sleep(1)
                return
            # except Exception as e:
            #     print e.message
            path = mydirs_[6] + "\\"+filename
            #path = path.encode('utf8')
            dict_str = extract_txt_doc(path,folderName,mydirs_,lena) #folderName - textboxBrowse.Text
            all_str_lst.append(dict_str)
            lena += 1

    error_files_count = 0
    for i in range(0, len(all_str_lst)):   #от 0 до len записей
        p = len(error_index)
        for v in all_str_lst[i]:
            if not v:
                #all_str_lst.pop(i)
                error_index.append(i)
        if len(error_index) > p:
            error_files_count += 1
    index_del=set(error_index)
    for index in sorted(index_del, reverse=True):
        del all_str_lst[index]   #Удаление строк из списка в которых есть ошибка
    #clear_content()
    print "Количество записей с ошибками: ", len(error_index)
    print "Количество файлов с ошибками: ", error_files_count
    # Выделение строк в таблице по количеству строк из документов
    n_rows = table_output_xlsx_11.getRowsCount() #количество строк
    rows_c = len(all_str_lst)                   #количество записей
    #print "n_rows,rows_c= ", n_rows ,rows_c
    A4_empty = table_output_xlsx_11.getCell("A4").getRawValue() == ''
    if rows_c < 1:
        pass
    elif rows_c > 0:
        if A4_empty and rows_c == 1:  # без вставки если пусто и 1 запись
            pass
        elif A4_empty and rows_c > 1:
            for i in range(11, 15):
                globals()['table_output_xlsx_%s' % i].insertRowAfter(n_rows - 1, copyRowStyle=True, rowsCount=rows_c-1)  # вставка если пусто для 2 и более
        elif table_output_xlsx_11.getCell("A4").getRawValue() <> '':
            for i in range(11, 15):
                globals()['table_output_xlsx_%s' % i].insertRowAfter(n_rows - 1, copyRowStyle=True, rowsCount=rows_c)  # вставка если не пусто
            n_rows = n_rows + 1
    number_rows = str(table_output_xlsx_11.getRowsCount())
    print "Количество строк в документе: ", number_rows
    # Записываем результат в таблицу
    #datetime1_end=convert_date(111)
    date_end=convert_time(date_end)
    write_table(all_str_lst, worker,date_end,n_rows) #Массив передастся в упорядоченном виде скорее всего
    set_cells_format(number_rows, worker)
    write_formules(worker, table_output_xlsx_11.getRowsCount(),n_rows)
    #error_data(error_index, worker)
    worker.ReportProgress(99, u"Сохранение XLSX.")
    for i in range(11, 15):
        globals()['document_xls_%s' % i].saveAs(globals()['output_file_url_xls_%s' % i])
    #raise Exception('This is the exception you expect to handle') #Аналог Throw для обработки исключений
    worker.ReportProgress(100, u"Готово.")
Ejemplo n.º 9
0
def main_(worker, folderName, mydirs_, date_end, workstatuspanel):
    log = []
    global application, table_output_xlsx
    application = sdk.Application()
    folder_url = mydirs_[6]  # Анкеты
    try:
        document_xls = application.loadDocument(
            mydirs_[11].encode('utf-8'))  # load Сводный
    except Exception as e:
        raise Exception(u"Невозможно открыть документ: " +
                        os.path.basename(mydirs_[11]))
    table_output_xlsx = document_xls.getBlocks().getTable(0)  # table Сводный
    all_str_lst = []
    error_index = []

    def split(s):
        for x, y in re.findall('(\d*)(\D*)', s):
            yield '', int(x or '0')
            yield y, 0

    def s(c):
        return list(split(c))

    regex_not_er = '(?<=_Ошибка).xlsx'
    regex_done = '№_\d+.*_Обработан\.xlsx'
    regex_not_prep = '(?<!_Обработан).xlsx'  # Попадание в список не обработанных, далее работаем только с ними.
    filtered_erorr = []
    for root, dirs, files in os.walk(mydirs_[0]):
        del dirs[:]  # go only one level deep
        filtered_erorr = [i for i in files if re.search(regex_not_er, str(i))]
    for root, dirs, files in os.walk(folder_url):
        del dirs[:]  # go only one level deep
        filtered_done = [i for i in files
                         if re.search(regex_done, str(i))]  # Обработанные
        filtered_not_prep = [
            i for i in files if re.search(regex_not_prep, str(i))
        ]  # Не обработанные
    filtered_erorr = sorted(filtered_erorr, key=s, reverse=True)
    filtered_done = sorted(filtered_done, key=s)
    print u"Количество файлов не обработанных: ", len(filtered_not_prep)
    if len(filtered_done + filtered_not_prep) == 0:
        raise Exception(u"Нет необходимых xlsx файлов в папке анкеты")

    lena = 1
    if len(filtered_not_prep) == 0:
        print u"Добавление записей не требуется!"
        worker.ReportProgress(100, u"Выполнено.")
        return
    else:
        if len(filtered_done) > 0:
            lena = int((filtered_done[len(filtered_done) -
                                      1]).split("_")[1]) + 1  # № последнего
            if filtered_erorr:
                lena_ = int((filtered_erorr[0]).split("_")[1]) + 1
                if lena < lena_:
                    lena = lena_
        for filename in filtered_not_prep:
            percentage = (filtered_not_prep.index(filename) *
                          91) / len(filtered_not_prep)
            # print worker.WorkerReportsProgress
            # try:
            worker.ReportProgress(percentage, u"Экспорт анкет.")
            if worker.CancellationPending == True:
                worker.ReportProgress(percentage, u"Отмена задания")
                time.sleep(1)
                return
            # except Exception as e:
            #     print e.message
            path = mydirs_[6] + "\\" + filename
            # path = path.encode('utf8')
            dict_str = extract_txt_doc(
                path, folderName, mydirs_, lena, log,
                workstatuspanel)  # folderName - Обработка Анкет
            all_str_lst.append(dict_str)
            lena += 1
    error_files_count = 0
    error_count = 0
    for k, i in enumerate(all_str_lst):
        error_count += i[-1]
        if i[-1] > 0:
            error_index.append(k)
            error_files_count += 1
    print u"Количество файлов с ошибками: ", error_files_count, \
        u"\nКоличество записей с ошибками: ", error_count
    if error_count > 0:
        log_file_rec(log, folderName)
    for index in sorted(error_index, reverse=True):
        del all_str_lst[index]  #удаление строк с ошибками
    # Выделение строк в таблице по количеству строк из документов
    n_rows = table_output_xlsx.getRowsCount(
    )  # количество строк в док перед вставкой
    rows_c = len(all_str_lst)  # количество записей
    # print u"n_rows,rows_c= ", n_rows ,rows_c
    A4_empty = table_output_xlsx.getCell("A4").getRawValue() == ''
    if rows_c < 1:
        pass
    elif rows_c > 0:
        if A4_empty and rows_c == 1:  # без вставки если пусто и 1 запись
            pass
        elif A4_empty and rows_c > 1:
            table_output_xlsx.insertRowAfter(
                n_rows - 1, copyRowStyle=True,
                rowsCount=rows_c - 1)  # вставка если пусто для 2 и более
        elif table_output_xlsx.getCell("A4").getRawValue() <> '':
            table_output_xlsx.insertRowAfter(
                n_rows - 1, copyRowStyle=True,
                rowsCount=rows_c)  # вставка если не пусто
            n_rows = n_rows + 1
    number_rows = str(table_output_xlsx.getRowsCount())
    print u"Количество строк в документе: ", number_rows
    # Записываем результат в таблицу
    table_output_xlsx.getCell("C1").setFormattedValue(
        str(date_end))  #Дата проведения
    write_table(all_str_lst, worker, date_end,
                n_rows)  # Массив передастся в упорядоченном виде скорее всего
    set_cells_format(number_rows, worker, n_rows)
    # error_data(error_index, worker)
    worker.ReportProgress(99, u"Сохранение XLSX.")
    try:
        document_xls.saveAs(mydirs_[11].encode('utf-8'))
    except Exception as e:
        #workstatuspanel.Text = u'Ошибка открыт документ!'
        raise Exception(u"Открыт документ: " + mydirs_[11].encode('utf-8'))
    # raise Exception('This is the exception you expect to handle') #Аналог Throw для обработки исключений
    worker.ReportProgress(100, u"Готово.")
Ejemplo n.º 10
0
def main_results(worker, mydirs_, count):
    regex_count = '^\d+$'
    if not re.search(regex_count, str(count)):
        raise Exception(u"Неправильно указана квота")
    application = sdk.Application()
    document_xls = application.loadDocument(mydirs_[11].encode('utf-8'))
    table_input = document_xls.getBlocks().getTable(0)

    scores_ = []
    n_rows = table_input.getRowsCount()

    def message_lose(table_input, i):
        last_name = table_input.getCell("B" + str(i)).getFormattedValue()
        first_name = table_input.getCell("C" + str(i)).getFormattedValue()
        bookmarks_lose.getBookmarkRange('name').replaceText(last_name + ' ' +
                                                            first_name)
        f_path = (mydirs_[1] + "\\" + '№' + str(i - 3) + ' ' + last_name +
                  ' ' + first_name + ' ' +
                  os.path.basename(mydirs_[5])).encode('utf-8')
        document_lose.saveAs((f_path))

    def message_win(table_input, i, fio):
        last_name, first_name = fio.split(" ")[0:2]
        bookmarks_win.getBookmarkRange('name').replaceText(last_name + ' ' +
                                                           first_name)
        f_path = (mydirs_[1] + "\\" + '№' + str(i - 3) + ' ' + last_name +
                  ' ' + first_name + ' ' +
                  os.path.basename(mydirs_[4])).encode('utf-8')
        document_win.saveAs((f_path))

    def paper_win(table_input, i, scores, fio):
        last_name, first_name, middle_name = fio.split(" ")[0:3]
        bookmarks_paper_win.getBookmarkRange('Last_name').replaceText(
            last_name)
        bookmarks_paper_win.getBookmarkRange('First_middle_name').replaceText(
            first_name + ' ' + middle_name)
        bookmarks_paper_win.getBookmarkRange('scores').replaceText(
            str(float("{0:.1f}".format(scores))))

        output_file = mydirs_[2] + "\\" + '№' + str(
            i - 3) + ' ' + last_name + ' ' + first_name + '.pdf'
        document_paper_win.exportAs(str(output_file), sdk.ExportFormat_PDFA1)

    template_win_doc = mydirs_[5].encode('utf-8')
    template_lose_doc = mydirs_[4].encode('utf-8')
    template_paper_win_doc = mydirs_[3].encode('utf-8')
    document_win = application.loadDocument(template_win_doc)
    bookmarks_win = document_win.getBookmarks()
    document_lose = application.loadDocument(template_lose_doc)
    bookmarks_lose = document_lose.getBookmarks()
    document_paper_win = application.loadDocument(template_paper_win_doc)
    bookmarks_paper_win = document_paper_win.getBookmarks()

    for i in range(4, n_rows + 1):
        if float(table_input.getCell("W" + str(i)).getFormattedValue()) > 10:
            fio = table_input.getCell('E' + str(i)).getRawValue()
            balls = float(table_input.getCell('AJ' + str(i)).getRawValue())
            id = int(table_input.getCell('AL' + str(i)).getRawValue())
            full_row_lst = [int(i), balls, id, fio]
            scores_.append(full_row_lst)

    scores_ = sorted(scores_, key=lambda x: (x[1], -x[2]),
                     reverse=True)[0:count]
    sorted_adr = [i[0] for i in scores_]
    k = 0
    for i in range(4, n_rows + 1):
        k += 1
        percentage = int((k * 100) / (n_rows - 3))
        worker.ReportProgress(percentage, u"Формирование грамот и писем.")
        if worker.CancellationPending == True:
            worker.ReportProgress(percentage, u"Отмена задания")
            time.sleep(1)
            return
        if i in sorted_adr:
            fio = scores_[sorted_adr.index(i)][3]
            scores = scores_[sorted_adr.index(i)][1]
            table_input.getCell("AK" + str(i)).setText('Да')
            message_win(table_input, i, fio)
            paper_win(table_input, i, scores, fio)
        else:
            table_input.getCell("AK" + str(i)).setText('Нет')
            message_lose(table_input, i)

    document_xls.saveAs(mydirs_[11].encode('utf8'))
Ejemplo n.º 11
0
def extract_txt_doc(path, folderName, mydirs_, lena, log, workstatuspanel):
    try:
        document_xlsinput = application.loadDocument(path.encode('utf-8'))
    except Exception as e:
        raise Exception(u"Невозможно открыть документ: " +
                        os.path.basename(path))
    table_input = document_xlsinput.getBlocks().getTable(0)

    last_name = table_input.getCell('C6').getRawValue()
    first_name = table_input.getCell('C8').getRawValue()
    middle_name = table_input.getCell('C10').getRawValue()

    date_birth = table_input.getCell('C12').getFormattedValue()
    country = table_input.getCell('C14').getRawValue()
    district = table_input.getCell('C15').getRawValue()
    post_index = table_input.getCell('C16').getRawValue()
    region = table_input.getCell('C18').getRawValue()
    city = table_input.getCell('C20').getRawValue()
    # address = table_input.getCell('C22').getRawValue()
    school = table_input.getCell('C22').getRawValue()
    school_address = table_input.getCell('C24').getRawValue()
    exp = table_input.getCell('C26').getRawValue()

    cert_1 = table_input.getCell('C28').getRawValue()
    cert_2 = table_input.getCell('C29').getRawValue()
    cert_3 = table_input.getCell('C30').getRawValue()
    cert_4 = table_input.getCell('C31').getRawValue()
    cert_5 = table_input.getCell('C32').getRawValue()
    cert = [cert_1, cert_2, cert_3, cert_4, cert_5]
    ball_list = [3, 5, 10, 5, 7]
    cert = [
        re.sub(u'[Дд][Аа]', 'Да', i.decode('utf8')).encode('utf8')
        for i in cert
    ]
    cert = [
        re.sub(u'[Нн][Ее][Тт]', 'Нет', i.decode('utf8')).encode('utf8')
        for i in cert
    ]
    diplom_list = [
        "Диплом 1 степени", "Диплом 2 степени", "Диплом 3 степени",
        "Диплом Почтового комиссара", 'Диплом "Наставника"'
    ]
    cert_list = [
        False if a == '' else a if a == "Нет" else b
        for a, b in zip(cert, diplom_list)
    ]  #Для того чтобы написать в сводном
    # файле название диплома или нет
    certflag = True
    da_count = [i for i in cert if re.search("Да", i)]
    if len(da_count) > 3:
        certflag = False
    cert_ball = [(a == 'Да') * b for a, b in zip(cert, ball_list)]

    phone = table_input.getCell('C33').getRawValue()
    email = table_input.getCell('C35').getRawValue()

    parent_fio = table_input.getCell('C37').getRawValue()
    parent_phone = table_input.getCell('C41').getRawValue()
    parent_email = table_input.getCell('C43').getRawValue()
    parent_work = table_input.getCell('C45').getRawValue()

    regex_error = '№_\d+.*_Ошибка\.xlsx'
    regex_date = '^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$'  # dd-mm-yyyy
    filename = str("№_" + str(lena) + "_" + last_name + "_" + first_name)
    # Раскрашиваем ячейки в анкетах с ошибками
    if not re.search(regex_date, str(date_birth)):
        date_birth = False
    dict_cells = {
        'C6': last_name,
        'C8': first_name,
        'C10': middle_name,
        'C12': date_birth,
        'C14': country,
        'C15': district,
        'C16': post_index,
        'C18': region,
        'C20': city,
        'C22': school,
        'C24': school_address,
        'C26': exp,
        'C27': certflag,
        'C28': cert_1,
        'C29': cert_2,
        'C30': cert_3,
        'C31': cert_4,
        'C32': cert_5,
        'C33': phone,
        'C35': email,
        'C37': parent_fio,
        'C41': parent_phone,
        'C43': parent_email,
        'C45': parent_work,
    }
    cell_properties = table_input.getCell('C6').getCellProperties()
    cell_properties.backgroundColor = sdk.ColorRGBA(255, 0, 0, 1)
    is_changed = False
    is_first_error = True

    error_count = 0
    filename_err = str(filename + "_Ошибка.xlsx")
    for key, val in dict_cells.iteritems():
        if not val:
            # Помечаем ошибки красным цветом в входном файле
            table_input.getCell(key).setCellProperties(cell_properties)
            log = log_file(filename_err, key, is_first_error, log)
            is_changed = True
            is_first_error = False
            error_count += 1
    if is_changed:
        # Ошибка
        # document_xlsinput.saveAs((mydirs_[0]+"\\"+filename).encode('utf-8'))
        if not (os.path.exists(mydirs_[0])):
            try:
                os.mkdir(mydirs_[0], 0o777)  # Папка Ошибки
                workstatuspanel.Text = u'Создана папка: ' + os.path.abspath(
                    mydirs_[0])
            except Exception:
                workstatuspanel.Text = u'Неудалось создать папку:' + os.path.basename(
                    mydirs_[0])
                raise Exception("Неудалось создать папку:" +
                                os.path.basename(mydirs_[0]))
        try:
            document_xlsinput.saveAs(
                (mydirs_[0] + "\\" + filename_err).encode('utf-8'))
            workstatuspanel.Text = u'Сохраняю файл с ошибкой:' + filename_err
        except Exception as e:
            raise Exception(u"Невозможно сохранить документ: " +
                            (mydirs_[0] + "\\" + filename_err))
        os.remove(path)
    else:
        filename_new = str(filename + "_Обработан.xlsx")
        if re.search(regex_error, str(os.path.basename(path))):
            lena = int(os.path.basename(path).split("_")[1])
            filename_new = str(os.path.basename(path)).replace(
                "Ошибка", "Обработан")
        os.rename(path, os.path.dirname(path) + "\\" + filename_new)

    full_row_lst = [
        last_name,
        first_name,
        middle_name,
        date_birth,
        country,
        district,
        post_index,
        region,
        city,
        school,
        school_address,
        exp,
        str(cert_list[0]) + ", " + str(cert_list[1]) + ", " +
        str(cert_list[2]) + ", " + str(cert_list[3]) + ", " +
        str(cert_list[4]),
        phone,
        email,
        parent_fio,
        parent_phone,
        parent_email,
        parent_work,
        cert_ball,
        certflag,
        lena,
        error_count,
    ]
    return full_row_lst
Ejemplo n.º 12
0
mydir7 = path_dirname_ + "\\" + u"Сводный файл (с учетом новой анкеты участника)_новый.xlsx"
mydir8 = path_dirname_ + "\\" + u"Артек_Программа _Дверь синего цвета_ (жюри 1)_исправленный.xlsx"
mydir9 = path_dirname_ + "\\" + u"Артек_Программа _Дверь синего цвета_ (жюри 2)_исправленный.xlsx"
mydir10 = path_dirname_ + "\\" + u"Артек_Программа _Дверь синего цвета_ (жюри 3)_исправленный.xlsx"
mydir11 = mydir + "\\" + os.path.basename(mydir7)

mydir12_out = mydir + "\\" + u"Артек_Программа _Дверь синего цвета_ (жюри 1)_результаты.xlsx"
mydir13_out = mydir + "\\" + u"Артек_Программа _Дверь синего цвета_ (жюри 2)_результаты.xlsx"
mydir14_out = mydir + "\\" + u"Артек_Программа _Дверь синего цвета_ (жюри 3)_результаты.xlsx"
mydirs_ = [
    mydir0, mydir1, mydir2, mydir3, mydir4, mydir5, mydir6, mydir7, mydir8,
    mydir9, mydir10, mydir11, mydir12_out, mydir13_out, mydir14_out
]

global application
application = sdk.Application()
document_xls = application.loadDocument(
    (path_dirname_ + "\\" + u"№_1_Егорова_Дарья.xlsx").encode('utf8'))
table_output_xlsx = document_xls.getBlocks().getTable(0)
first_names_F = [
    "Дарья", "Ольга", "Анастасия", "Анна", "Мария", "Алина", "Ирина",
    "Екатерина", "Арина"
]
first_names_M = [
    "Алан",
    "Александр",
    "Алексей",
    "Альберт",
    "Анатолий",
    "Андрей",
    "Антон",
Ejemplo n.º 13
0
# -*- coding: utf-8 -*-
import os, time, itertools
from datetime import datetime
from MyOfficeSDKDocumentAPI import DocumentAPI as sdk
from string import ascii_uppercase

global application
application = sdk.Application()
cell_properties_win = sdk.CellProperties()
cell_properties_win.backgroundColor = sdk.ColorRGBA(193, 242, 17, 255)
cell_properties_lose = sdk.CellProperties()
cell_properties_lose.backgroundColor = sdk.ColorRGBA(108, 122, 137, 255)


def message(table_input, i, template, mydirs_):
    document = application.loadDocument(template)
    bookmarks = document.getBookmarks()
    last_name = table_input.getCell("B" + str(i)).getFormattedValue()
    first_name = table_input.getCell("C" + str(i)).getFormattedValue()
    bookmarks.getBookmarkRange('name').replaceText(last_name + ' ' +
                                                   first_name)
    f_path = (mydirs_[17] + "\\" + '№' + str(i - 3) + ' ' + last_name + ' ' +
              first_name + ' ' + os.path.basename(template)).encode('utf-8')
    document.saveAs((f_path))


def iter_all_strings():
    for size in itertools.count(1):
        for s in itertools.product(ascii_uppercase, repeat=size):
            yield "".join(s)
Ejemplo n.º 14
0
mydir7 = path_dirname_ + "\\" + u"Сводный файл (с учетом новой анкеты участника)_новый.xlsx"
mydir8 = path_dirname_ + "\\" + u"Артек_Программа _Дверь синего цвета_ (жюри 1)_исправленный.xlsx"
mydir9 = path_dirname_ + "\\" + u"Артек_Программа _Дверь синего цвета_ (жюри 2)_исправленный.xlsx"
mydir10 = path_dirname_ + "\\" + u"Артек_Программа _Дверь синего цвета_ (жюри 3)_исправленный.xlsx"
mydir11 = mydir + "\\" + os.path.basename(mydir7)

mydir12_out = mydir + "\\" + u"Артек_Программа _Дверь синего цвета_ (жюри 1)_результаты.xlsx"
mydir13_out = mydir + "\\" + u"Артек_Программа _Дверь синего цвета_ (жюри 2)_результаты.xlsx"
mydir14_out = mydir + "\\" + u"Артек_Программа _Дверь синего цвета_ (жюри 3)_результаты.xlsx"
mydirs_ = [
    mydir0, mydir1, mydir2, mydir3, mydir4, mydir5, mydir6, mydir7, mydir8,
    mydir9, mydir10, mydir11, mydir12_out, mydir13_out, mydir14_out
]

global application
application = sdk.Application()
cell_properties = sdk.CellProperties()
cell_properties.backgroundColor = sdk.ColorRGBA(193, 242, 17, 255)


def iter_all_strings():
    for size in itertools.count(1):
        for s in itertools.product(ascii_uppercase, repeat=size):
            yield "".join(s)


def list_xls(rang):
    lst_addr = []
    for s in iter_all_strings():
        lst_addr.append(s)
        if s == rang:
Ejemplo n.º 15
0
def main_results(worker, mydirs_):
    def load_doc(mydirs_):
        input_file_url_xls = mydirs_.encode('utf-8')  # Output с размещением системы рейтингования
        document_xls = application.loadDocument(input_file_url_xls)  # load Сводный
        table_output_xlsx = document_xls.getBlocks().getTable(0)  # table Сводный
        return table_output_xlsx, document_xls

    def message(table_input, i, mydirs_, int_status):
        last_name = table_input.getCell("B" + str(i)).getRawValue()
        first_name = table_input.getCell("C" + str(i)).getRawValue()
        if int_status==1: #Победитель
            cast=table_input.getCell("AL" + str(i)).getRawValue()
            date_begin = table_input.getCell("AM" + str(i)).getRawValue()
            date_last = table_input.getCell("AN" + str(i)).getRawValue()
            date = table_input.getCell("AO" + str(i)).getRawValue()
            bookmarks_win.getBookmarkRange('name').replaceText(last_name + ' ' + first_name)
            bookmarks_win.getBookmarkRange('cast').replaceText(cast)
            bookmarks_win.getBookmarkRange('date_begin').replaceText(date_begin)
            bookmarks_win.getBookmarkRange('date_last').replaceText(date_last)
            bookmarks_win.getBookmarkRange('date').replaceText(date)
            f_path = (mydirs_[1] + "\\" + '№' + str(i - 3) + ' ' + last_name + ' ' + first_name + ' ' + os.path.basename(
                mydirs_[20])).encode('utf-8')
            document_win.saveAs((f_path))
        elif int_status == 2: #Не прошел
            scores = table_input.getCell("AJ" + str(i)).getFormattedValue()
            bookmarks_lose.getBookmarkRange('name').replaceText(last_name + ' ' + first_name)
            bookmarks_lose.getBookmarkRange('scores').replaceText(scores)
            f_path = (mydirs_[1] + "\\" + '№' + str(i - 3) + ' ' + last_name + ' ' + first_name + ' ' + os.path.basename(
                mydirs_[21])).encode('utf-8')
            document_lose.saveAs((f_path))
        elif int_status == 3: #Резерв
            scores = table_input.getCell("AJ" + str(i)).getFormattedValue()
            number_pos = table_input.getCell("AP" + str(i)).getRawValue()
            date_ = table_input.getCell("AQ" + str(i)).getRawValue()
            bookmarks_reserve.getBookmarkRange('name').replaceText(last_name + ' ' + first_name)
            bookmarks_reserve.getBookmarkRange('scores').replaceText(scores)
            bookmarks_reserve.getBookmarkRange('number').replaceText(number_pos)
            bookmarks_reserve.getBookmarkRange('date').replaceText(date_)
            f_path = (mydirs_[1] + "\\" + '№' + str(i - 3) + ' ' + last_name + ' ' + first_name + ' ' + os.path.basename(
                mydirs_[19])).encode('utf-8')
            document_reserve.saveAs((f_path))


    def paper_win(table_input, i,mydirs_):
        last_name = table_input.getCell("B" + str(i)).getRawValue()
        first_name = table_input.getCell("C" + str(i)).getRawValue()
        middle_name = table_input.getCell("D" + str(i)).getRawValue()
        scores = table_input.getCell("AJ" + str(i)).getFormattedValue()
        bookmarks_paper_win.getBookmarkRange('Last_name').replaceText(last_name)
        bookmarks_paper_win.getBookmarkRange('First_middle_name').replaceText(first_name + ' ' + middle_name)
        bookmarks_paper_win.getBookmarkRange('scores').replaceText(scores)
        output_file = mydirs_[2] + "\\" + '№' + str(i - 3) + ' ' + last_name + ' ' + first_name + '.pdf'
        document_paper_win.exportAs(str(output_file), sdk.ExportFormat_PDFA1)

    application = sdk.Application()
    template_win_doc = mydirs_[4].encode('utf-8')
    template_lose_doc = mydirs_[5].encode('utf-8')
    template_paper_win_doc = mydirs_[3].encode('utf-8')
    template_reserve_doc = mydirs_[18].encode('utf-8')
    document_win = application.loadDocument(template_win_doc)
    bookmarks_win = document_win.getBookmarks()
    document_lose = application.loadDocument(template_lose_doc)
    bookmarks_lose = document_lose.getBookmarks()
    document_paper_win = application.loadDocument(template_paper_win_doc)
    bookmarks_paper_win = document_paper_win.getBookmarks()
    document_reserve=application.loadDocument(template_reserve_doc)
    bookmarks_reserve=document_reserve.getBookmarks()

    table_output_xlsx_main, document_xls_main = load_doc(mydirs_[11])
    n_rows_count = table_output_xlsx_main.getRowsCount()

    k = 0
    for i in range(4, n_rows_count + 1):
        k += 1
        percentage = int((k * 100) / (n_rows_count - 3))
        n_rows = str(i)
        status=table_output_xlsx_main.getCell("AK" + n_rows).getRawValue()
        all_scores=float(table_output_xlsx_main.getCell("W" + n_rows).getFormattedValue())
        worker.ReportProgress(percentage, u"Формирование грамот и писем.")
        if worker.CancellationPending == True:
            worker.ReportProgress(percentage, u"Отмена задания")
            time.sleep(1)
            return
        if all_scores >= 10 and re.search('[Пп]обедитель',status):
            int_status=1
            message(table_output_xlsx_main, i, mydirs_, int_status)
            paper_win(table_output_xlsx_main, i,mydirs_)
        elif all_scores >= 10 and re.search('[Нн]е прошел',status):
            int_status = 2
            message(table_output_xlsx_main, i, mydirs_, int_status)
        elif re.search('[Рр]езерв',status):
            int_status = 3
            message(table_output_xlsx_main, i, mydirs_, int_status)