ABAP-动态内表的实现
什么是动态内表?动态内表就是字段的数量不是固定的,可以根据实际情况来改变内表的字段数量。
例如程序输入3行3列
ALV输出
如果输入10列3行
ALV输出
源代码
1 REPORT y4_b4_test MESSAGE-ID zmess . 2 3 FIELD-SYMBOLS: <fs_table> TYPE STANDARD TABLE, 4 <fs_line> TYPE any. 5 6 DATA: lr_table TYPE REF TO data, 7 lr_line TYPE REF TO data. 8 9 *ALV字段列表。 10 DATA: gt_fieldcat TYPE lvc_t_fcat. 11 12 PARAMETERS: p_row TYPE i DEFAULT 3, 13 p_col TYPE i DEFAULT 3. 14 15 START-OF-SELECTION. 16 PERFORM frm_init_data. 17 18 END-OF-SELECTION. 19 PERFORM frm_display_alv. 20 21 FORM frm_init_data . 22 23 " 初始化列 24 DO p_col TIMES. 25 DATA(lv_comps) = |COL{ sy-index }|. 26 DATA(lv_text) = |列{ sy-index }|. 27 PERFORM frm_fill_fieldcat USING sy-index lv_comps lv_text. 28 ENDDO. 29 30 SORT gt_fieldcat BY col_pos. 31 32 " 根据列创建动态内表 33 CALL METHOD cl_alv_table_create=>create_dynamic_table 34 EXPORTING 35 it_fieldcatalog = gt_fieldcat 36 IMPORTING 37 ep_table = lr_table. 38 39 " 将表对象分配给指针 40 ASSIGN lr_table->* TO <fs_table>. 41 42 " 根据表对象创建行对象 43 CREATE DATA lr_line LIKE LINE OF <fs_table>. 44 45 " 将行对象分配给指针 46 ASSIGN lr_line->* TO <fs_line>. 47 48 "初始化行 49 DO p_row TIMES . 50 51 APPEND INITIAL LINE TO <fs_table> . 52 53 ENDDO . 54 55 DATA:lv_index TYPE i . 56 57 "把每一行的数据赋值 58 LOOP AT <fs_table> ASSIGNING FIELD-SYMBOL(<a>) . 59 60 lv_index = lv_index + 1 . 61 62 IF <a> IS ASSIGNED . 63 64 DO p_col TIMES . 65 66 DATA(lv_comp) = |COL{ sy-index }|. 67 "用指针指向这个字段 68 ASSIGN COMPONENT lv_comp OF STRUCTURE <a> TO FIELD-SYMBOL(<fs_comp>). 69 IF sy-subrc = 0. 70 <fs_comp> = |{ lv_comp }--{ lv_index }|. 71 ENDIF. 72 73 ENDDO . 74 75 ENDIF . 76 77 ENDLOOP . 78 79 ENDFORM. 80 81 FORM frm_fill_fieldcat USING p_col p_fieldname p_text. 82 83 APPEND INITIAL LINE TO gt_fieldcat ASSIGNING FIELD-SYMBOL(<fs_field>). 84 IF <fs_field> IS ASSIGNED. 85 <fs_field>-col_pos = p_col. 86 <fs_field>-fieldname = p_fieldname. 87 <fs_field>-scrtext_m = p_text. 88 ENDIF. 89 90 ENDFORM. 91 92 FORM frm_display_alv . 93 94 CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY_LVC' 95 EXPORTING 96 i_callback_program = sy-cprog 97 it_fieldcat_lvc = gt_fieldcat 98 i_default = 'X' 99 i_save = 'A' 100 TABLES 101 t_outtab = <fs_table>. 102 103 ENDFORM.