Выкладываю исходный код программы которая позволяет загружать и выгружать данные из таблиц в текстовый файл
*&---------------------------------------------------------------------* *& Report ZBC_IMP_EXP_TABLE *& *&---------------------------------------------------------------------* *& *& *&---------------------------------------------------------------------* line-count 65 no standard page heading.. gc_name_rec type char2 value 'A0', gc_header_rec type char2 value 'A1', gc_record_rec type char2 value 'A2', gc_0d_replace type char6 value '#~0D~#', " Чем заменить перевод строки gc_0a_replace type char6 value '#~0A~#'. " Чем заменить перевод строки rectype type char2, " Тип записи файла line type string, " Строка файла, поля разделены разделителями end of lty_tabline, begin of lty_fieldname, fieldname type dd03l-fieldname, end of lty_fieldname. lty_t_fieldname type table of lty_fieldname. select-options: s_tables for dd02l-tabname. p_imp type c radiobutton group 1, p_del type c as checkbox default ' '. p_cond2 type text50 modif id exp, p_cond3 type text50 modif id exp. *---------------------------------------------------------------------- *---------------------------------------------------------------------- at user-command. *---------------------------------------------------------------------- perform main_export. else. perform main_import. *&---------------------------------------------------------------------* *& Form output *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* else. else. modify screen. *&---------------------------------------------------------------------* *& Form export_table_to_file *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* * --> p1 text * <-- p2 text *----------------------------------------------------------------------* changing ct_contents type lty_t_tabline value(c_rc) type sysubrc. lr_data type ref to data, lv_value type string, lv_tabix type sy-tabix, <ls_fieldname> type lty_fieldname, <lt_table> type table, <ls_line> type any, <lv_value> type any. * Check if table exists select single tabname into u_tabname from dd02l where tabname = u_tabname and tabclass = 'TRANSP'. into lv_dummy. c_rc = 1. * Заголовок - имя таблицы <ls_tabline>-rectype = gc_name_rec. <ls_tabline>-line = u_tabname. * Заголовок таблицы (имена полей) <ls_tabline>-rectype = gc_header_rec. * Строки таблицы create data lr_data type table of (u_tabname). " Применяем подходящие условия try. select * from (u_tabname) into table <lt_table> where (p_cond1). exit. catch cx_sy_dynamic_osql_semantics. try. select * from (u_tabname) into table <lt_table> where (p_cond2). exit. catch cx_sy_dynamic_osql_semantics. try. select * from (u_tabname) into table <lt_table> where (p_cond3). exit. catch cx_sy_dynamic_osql_semantics. select * from (u_tabname) into table <lt_table>. <ls_tabline>-rectype = gc_record_rec. lv_tabix = sy-tabix. lv_value = <lv_value>. else. clear lv_value. with gc_0d_replace. with gc_0a_replace. *&---------------------------------------------------------------------* *& Form get_table_fields *&---------------------------------------------------------------------* * Возвращает имена полей таблицы без mandt *----------------------------------------------------------------------* * --> p1 text * <-- p2 text *----------------------------------------------------------------------* changing ct_fields type lty_t_fieldname. select fieldname from dd03l into table ct_fields where tabname = u_tabname and precfield = space " Исключаем include and domname <> 'MANDT'. " Исключаем мандант *&---------------------------------------------------------------------* *& Form get_all_tabnames_from_file *&---------------------------------------------------------------------* * Возвращает список таблиц, которые есть в файле *----------------------------------------------------------------------* * --> p1 text * <-- p2 text *----------------------------------------------------------------------* changing ct_names type string_table. where rectype = gc_name_rec. *&---------------------------------------------------------------------* *& Form check_table_structure *&---------------------------------------------------------------------* * Выполняет проверку структуры таблицы, возвращает флаг * успешности-неуспешности и список ошибок если неуспех *----------------------------------------------------------------------* * --> p1 text * <-- p2 text *----------------------------------------------------------------------* ut_content type lty_t_tabline changing ct_return type bapiret2_t value(c_rc) type sysubrc. lv_text type string, lt_fields_file type table of lty_fieldname, lt_fields_sap type table of lty_fieldname, lv_num_fields_sap type i, lv_num_fields_file type i, lv_not_found type wdy_boolean. <ls_field_file> type lty_fieldname, <ls_field_sap> type lty_fieldname. * Find the table record read table ut_content with key rectype = gc_name_rec line = u_tabname transporting no fields. c_rc = 1. * Look for header description line to compare to the database state lv_index = sy-tabix. lv_index = lv_index + 1. perform get_first_header_after_line using u_tabname ut_content lv_index changing lt_fields_file[] c_rc. * Get fields list from database and perform the comparison describe table lt_fields_sap lines lv_num_fields_sap. describe table lt_fields_file lines lv_num_fields_file. lv_index = sy-tabix. lv_not_found = abap_false. unassign <ls_field_sap>. read table lt_fields_sap index sy-tabix assigning <ls_field_sap>. lv_not_found = abap_true. else. lv_not_found = abap_true. <ls_field_file>-fieldname 'таблицы'(005) u_tabname ', имеющееся в файле'(006) into lv_text separated by space. c_rc = 1. read table lt_fields_file with key fieldname = <ls_field_sap>-fieldname transporting no fields. 'таблицы'(005) u_tabname ', имеющееся в SAP'(008) into lv_text separated by space. c_rc = 1. *&---------------------------------------------------------------------* *& Form modify_dbtab_from_file *&---------------------------------------------------------------------* * Выполняет модицикацию таблицы из файла *----------------------------------------------------------------------* * --> p1 text * <-- p2 text *----------------------------------------------------------------------* ut_content type lty_t_tabline value(u_delete) type wdy_boolean changing value(c_rc) type sysubrc. lv_tabix type sy-tabix, lr_data type ref to data, lt_values type table of string, lv_value type string, lv_clidep type dd02l-clidep. <ls_dbtab_line> type any, <lv_value> type any, <ls_fieldname> type lty_fieldname. * Find the table record read table ut_content with key rectype = gc_name_rec line = u_tabname transporting no fields. into lv_dummy. c_rc = 1. lv_tabix = sy-tabix + 1. select single clidep into lv_clidep from dd02l where tabname = u_tabname and tabclass = 'TRANSP'. create data lr_data type (u_tabname). from lv_tabix. "WHERE rectype = gc_record_rec. " Началась следующая таблица - выходим exit. lv_tabix = sy-tabix. " Если таблица зависима от манданта, то номер поля будет на 1 больше lv_tabix = lv_tabix + 1. <lv_value> = lv_value. *&---------------------------------------------------------------------* *& Form get_first_header_after_line *&---------------------------------------------------------------------* * Технический код: возвращает поля первого заголовка файла * в загруженном контенте после определенной строки этого файла *----------------------------------------------------------------------* * --> p1 text * <-- p2 text *----------------------------------------------------------------------* ut_content type lty_t_tabline value(u_line_from) type i changing ct_header_fields type lty_t_fieldname value(c_rc) type sysubrc. from u_line_from where rectype = gc_header_rec. exit. 'не найдена строка заголовка в файле'(010) into lv_dummy. c_rc = 1. * Parse the header string in order to get field list from it *&---------------------------------------------------------------------* *& Form load_contents_from_file *&---------------------------------------------------------------------* * Загружает файл с диска во внутреннюю таблицу *----------------------------------------------------------------------* * --> p1 text * <-- p2 text *----------------------------------------------------------------------* form load_contents_from_file using u_filename changing ct_content type lty_t_tabline value(c_rc) type sysubrc. line(3000) type c, end of lt_data_tab. lv_contents type string, lt_lines type table of string, lv_text type string. lv_filename = u_filename. call method cl_gui_frontend_services=>gui_upload exporting filename = lv_filename read_by_line = abap_false changing data_tab = lt_data_tab[] exceptions file_open_error = 1 file_read_error = 2 no_batch = 3 gui_refuse_filetransfer = 4 invalid_type = 5 no_authority = 6 unknown_error = 7 bad_data_format = 8 header_not_allowed = 9 separator_not_allowed = 10 header_too_long = 11 unknown_dp_error = 12 access_denied = 13 dp_out_of_memory = 14 disk_full = 15 dp_timeout = 16 not_supported_by_gui = 17 error_no_gui = 18 others = 19. c_rc = sy-subrc. loop at lt_data_tab. * Каждая строка файла содержит вид записи (2 символа), разделитель, а затем * уже информацию в зависимости от вида записи with cl_abap_char_utilities=>cr_lf(1). with cl_abap_char_utilities=>cr_lf+1(1). *&---------------------------------------------------------------------* *& Form save_contents_to_file *&---------------------------------------------------------------------* * Сохраняет содержимое файла из внутренней таблицы на диск *----------------------------------------------------------------------* * --> p1 text * <-- p2 text *----------------------------------------------------------------------* form save_contents_to_file using u_filename ut_content type lty_t_tabline changing value(c_rc) type sysubrc. line(3000) type c, end of lt_data_tab. lv_lines type i, lv_filename type string. lv_filename = u_filename. lv_lines = lines( ut_content ). into lv_string. call function 'SCMS_STRING_TO_FTEXT' exporting text = lv_string ftext_tab = lt_data_tab[]. call method cl_gui_frontend_services=>gui_download exporting filename = lv_filename write_lf = abap_false write_lf_after_last_line = abap_false changing data_tab = lt_data_tab[] "trunc_trailing_blanks = abap_true exceptions file_write_error = 1 no_batch = 2 gui_refuse_filetransfer = 3 invalid_type = 4 no_authority = 5 unknown_error = 6 header_not_allowed = 7 separator_not_allowed = 8 filesize_not_allowed = 9 header_too_long = 10 dp_error_create = 11 dp_error_send = 12 dp_error_write = 13 unknown_dp_error = 14 access_denied = 15 dp_out_of_memory = 16 disk_full = 17 dp_timeout = 18 file_not_found = 19 dataprovider_exception = 20 control_flush_error = 21 not_supported_by_gui = 22 error_no_gui = 23 others = 24. c_rc = sy-subrc. *&---------------------------------------------------------------------* *& Form open_file_name *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* * -->UC_FILE text *----------------------------------------------------------------------* ld_str type string, ld_rc type i. * Отображаем стандартный диалог открытия файла ld_str = 'Выберите файл для загрузки'(011). call method cl_gui_frontend_services=>file_open_dialog exporting window_title = ld_str file_filter = 'Text files|*.txt' multiselection = ' ' changing file_table = lt_filetable[] rc = ld_rc. "#EC NOTEXT * Записываем имя файла в параметр read table lt_filetable index 1 into uc_file. *&---------------------------------------------------------------------* *& Form main_export *&---------------------------------------------------------------------* * Главная процедура, выполняющая экспорт *----------------------------------------------------------------------* * --> p1 text * <-- p2 text *----------------------------------------------------------------------* form main_export. lv_rc type sysubrc, lt_log type table of bapiret2, lv_text type string. * Формируем файл на основе всех таблиц во внутренней таблице perform add_table_to_file using <ls_sel_table>-low changing lt_contents[] lv_rc. lv_text = 'Сохранение данных в файл'(014). * Сохраняем сформированную таблицу в файл perform save_contents_to_file using p_file lt_contents[] changing lv_rc. *&---------------------------------------------------------------------* *& Form main_import *&---------------------------------------------------------------------* * Главная процедура, выполняющая импорт *----------------------------------------------------------------------* * --> p1 text * <-- p2 text *----------------------------------------------------------------------* form main_import. lv_rc type sysubrc, lt_names type table of string, lv_name type dd02l-tabname, lt_log type table of bapiret2, lt_return type table of bapiret2, lv_global_rc type sysubrc, lv_text type string, lv_lines type i, lv_ans type char1. lv_text = 'Загрузка данных'(016). * Load file to internal table perform load_contents_from_file using p_file changing lt_contents lv_rc. lv_text = 'Проверка данных'(017). * List tables stored in file perform get_all_tabnames_from_file using lt_contents changing lt_names. * Check each table, table structure must match perform check_table_structure using lv_name lt_contents[] changing lt_return lv_rc. lv_global_rc = lv_rc. * Delete tables not matching the selection delete lt_names. perform msg_to_ret2_string using 'Ни один из содержащихся в файле таблиц не подходит под критерии выбора, ничего не загружено'(020) 'W' changing lt_log[]. * Several user asks and dialogs lv_lines = lines( lt_names ). lv_text = lv_lines. condense lv_text. into lv_text separated by space. call function 'POPUP_TO_CONFIRM' exporting * TITLEBAR = ' ' * DIAGNOSE_OBJECT = ' ' text_question = lv_text * TEXT_BUTTON_1 = 'Ja'(001) * ICON_BUTTON_1 = ' ' * TEXT_BUTTON_2 = 'Nein'(002) * ICON_BUTTON_2 = ' ' * DEFAULT_BUTTON = '1' * DISPLAY_CANCEL_BUTTON = 'X' * USERDEFINED_F1_HELP = ' ' * START_COLUMN = 25 * START_ROW = 6 * POPUP_TYPE = * IV_QUICKINFO_BUTTON_1 = ' ' * IV_QUICKINFO_BUTTON_2 = ' ' importing answer = lv_ans * TABLES * PARAMETER = exceptions others = 1. with sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. call function 'POPUP_TO_CONFIRM' exporting * TITLEBAR = ' ' * DIAGNOSE_OBJECT = ' ' text_question = 'Хотите ли вы посмотреть список загружаемых таблиц?'(025) * TEXT_BUTTON_1 = 'Ja'(001) * ICON_BUTTON_1 = ' ' * TEXT_BUTTON_2 = 'Nein'(002) * ICON_BUTTON_2 = ' ' * DEFAULT_BUTTON = '1' * DISPLAY_CANCEL_BUTTON = 'X' * USERDEFINED_F1_HELP = ' ' * START_COLUMN = 25 * START_ROW = 6 * POPUP_TYPE = * IV_QUICKINFO_BUTTON_1 = ' ' * IV_QUICKINFO_BUTTON_2 = ' ' importing answer = lv_ans * TABLES * PARAMETER = exceptions others = 1. with sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. call function 'POPUP_WITH_TABLE' exporting endpos_col = 50 endpos_row = 30 startpos_col = 10 startpos_row = 10 titletext = 'Список загружаемых таблиц'(026) valuetab = lt_names[] exceptions break_off = 1 others = 2. with sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. * Perform load perform modify_dbtab_from_file using lv_name lt_contents[] p_del changing lv_rc. rollback work. "#EC CI_ROLLBACK commit work. lv_text = lv_lines. condense lv_text. *&---------------------------------------------------------------------* *& Form show_log *&---------------------------------------------------------------------* * Показывает лог на экран *----------------------------------------------------------------------* * --> p1 text * <-- p2 text *----------------------------------------------------------------------* call function 'SUSR_DISPLAY_LOG' exporting display_in_popup = abap_true log_title = 'Журнал обработки программы'(030) * IT_LOG_SPROT = it_log_bapiret2 = ut_log[] exceptions others = 1. with sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. *&---------------------------------------------------------------------* *& Form statusbar_message *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* * -->UD_PERCENT text * -->UD_TEXT text *----------------------------------------------------------------------* call function 'SAPGUI_PROGRESS_INDICATOR' exporting percentage = ud_percent text = ud_text. *&---------------------------------------------------------------------* *& Form msg_to_ret2_string *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* * -->I_MESSAGE_TEXT text * -->VALUE(I_MSGTY) text * -->CT_RETURN text *----------------------------------------------------------------------* form msg_to_ret2_string using i_message_text value(i_msgty) type symsgty changing ct_return type bapiret2_t. lv_len type i, and i_msgty <> 'S' and i_msgty <> 'W' and i_msgty <> 'E' and i_msgty <> 'A' and i_msgty <> 'X'. i_msgty = 'S'. ls_msg-msgid = 'CLHP'. ls_msg-msgno = '000'. ls_msg-msgty = i_msgty. lv_len = strlen( i_message_text ). ls_msg-msgv1 = i_message_text. ls_msg-msgv1 = i_message_text(50). ls_msg-msgv2 = i_message_text+50. ls_msg-msgv1 = i_message_text(50). ls_msg-msgv2 = i_message_text+50(50). ls_msg-msgv3 = i_message_text+100. ls_msg-msgv1 = i_message_text(50). ls_msg-msgv2 = i_message_text+50(50). ls_msg-msgv3 = i_message_text+100(50). ls_msg-msgv4 = i_message_text+150. with ls_msg-msgv1 ls_msg-msgv2 ls_msg-msgv3 ls_msg-msgv4 into lv_dummy. *&---------------------------------------------------------------------* *& Form log_msg *&---------------------------------------------------------------------* * text *----------------------------------------------------------------------* * -->CT_RETURN text *----------------------------------------------------------------------* <ls_return>-id = sy-msgid. <ls_return>-number = sy-msgno. <ls_return>-type = sy-msgty. <ls_return>-message_v1 = sy-msgv1. <ls_return>-message_v2 = sy-msgv2. <ls_return>-message_v3 = sy-msgv3. <ls_return>-message_v4 = sy-msgv4.