将分号分隔的字符串转换为表结构?



我需要一些帮助将字符串转换为ITAB。

LOOP AT LT_0111_FILE INTO LV_STRING.
SPLIT LV_STRING AT ';' INTO TABLE LT_0111.
DO GV_COMP TIMES.
READ TABLE LT_0111 ASSIGNING <LV> INDEX SY-INDEX.
IF <LV> IS NOT INITIAL.
ASSIGN COMPONENT SY-INDEX OF STRUCTURE <STRUCT> TO <LV_COMP>.
IF <LV_COMP> IS ASSIGNED.
<LV_COMP> = <LV>.
ENDIF.
ENDIF.
ENDDO.
INSERT <STRUCT> INTO TABLE <TABLE>.
ENDLOOP.

LT_0111_FILE中的表PA0111是带分隔符";"的字符串。现在我需要分配的各个领域从PA0111 stringtable到的字段结构。

我不想为每个字段单独做这个,因为字段将被动态创建。

此代码适用于字符字段,但不适用于数字。txt文件中会有数字0 00和移动他们的字段结构会给一个错误,因为数量是0.00 .

Thanks for the help

当你有一个未知的结构,想知道它有什么字段,这些字段有什么属性,那么你可以使用运行时类型信息类。

首先,获取目标结构的类型描述。

DATA lo_struct_description TYPE REF TO cl_abap_structdescr.
lo_struct_description ?= cl_abap_typedescr=>describe_by_data( <struct> ).

这里需要使用转换运算符?=,因为describe_by_data的返回值是一个泛型的cl_abap_typedescr知道它必须是一个结构,但是类不知道。它也可以是一个表、简单类型或对对象的引用。但是如果你能保证它是一个结构,你可以将它向上转换为cl_abap_structdescr

现在你可以得到一个表,描述结构的所有字段:

DATA lt_components TYPE abap_component_tab.
lt_components = lo_struct_description->get_components( ).

该表包含这些组件的名称和类型。因此,不用使用do循环并按索引使用ASSIGN COMPONENT,而是可以按名称使用ASSIGN COMPONENT并按组件表使用LOOP AT。然后你可以根据它的类型来处理每个字段:

LOOP AT lt_components INTO ls_component.
READ TABLE lt_0111 ASSIGNING <lv_in> INDEX sy-tabix.
IF sy-subrc = 0.
ASSIGN COMPONENT ls_component-name OF STRUCTURE <struct> TO <lv_out>.
IF sy-subrc = 0.
CASE ls_component-type->type_kind.
WHEN cl_abap_datadescr=>typekind_date.
" Special handling for dates
WHEN cl_abap_datadescr=>typekind_packed.
" Special handling for decimal numbers

" Check the other constants cl_abap_datadescr=>typekind_* for all the other types
" you might encounter in your use-case and which might require special treatment.
WHEN OTHERS.
" Probably just copyable. If not, you will get a runtime error here and need 
" to implement special handling for this particular type_kind.
<lv_out> = <lv_in>.
ENDCASE.
ENDIF.
ENDIF.
ENDLOOP.

实际上我更喜欢Philips的解决方案,它在类型处理方面更防错,更全面,但为了多样性,我将添加这个快速肮脏的解决方案。

可以使用cl_rsda_csv_converter辅助类的方法:

DATA: input TYPE TABLE OF string.
TYPES t_itab TYPE TABLE OF pa0009 WITH EMPTY KEY.
DATA(dref) = NEW t_itab(  ).
APPEND ` 800;90051099;0;;;99991231;20080501;000;20100312;HORVATLU;;;;;;;;;;;;;;;46456.89;HUF;0.00;;0;;;;;HU;;;;;;;;;;;;;;;;00;;;;00000000;;;;; ` TO input.
APPEND ` 800;99000005;0;;;99991231;20170101;000;20170220;GUNASHMA;;;;;;;;;;;;;;;5564665.00;EUR;0.00;;0;;;;;DE;28511111;123;;;;;;;;;;;;;;00;;;;00000000;;;;; ` TO input.
DATA: ls_line TYPE LINE OF t_itab.
LOOP AT input ASSIGNING FIELD-SYMBOL(<fs_s>).
* creating converter
DATA(lo_csv) = cl_rsda_csv_converter=>create( i_separator = ';' ).
* Process records
lo_csv->csv_to_structure( EXPORTING i_data = <fs_s> IMPORTING e_s_data = ls_line ).
* inserting into itab
INSERT ls_line INTO TABLE dref->*.
ENDLOOP.

最新更新