コード例 #1
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)
コード例 #2
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"Готово.")
コード例 #3
0
ファイル: MyOfficeV4_1_1.py プロジェクト: dalred/MyOfficeV4
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"Готово.")
コード例 #4
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"Готово.")
コード例 #5
0
ファイル: Results_v3_3.py プロジェクト: dalred/MyOfficeV4
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'))
コード例 #6
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"Готово.")
コード例 #7
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 = [
    "Алан",
    "Александр",
    "Алексей",
    "Альберт",
    "Анатолий",
    "Андрей",
    "Антон",
コード例 #8
0
ファイル: Results_v3_4.py プロジェクト: dalred/MyOfficeV4
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)