DATA: BEGIN OF ITAB OCCURS 0,
FIELD1 TYPE I,
FIELD2 TYPE C,
END OF ITAB.
但有時欄位可能依特殊條件而需要增加,則此時就必需要自訂 Internal Table。
宣告:
"指標 for 動態 Table 與 Work Area
FIELD-SYMBOLS: <DYN_TABLE> TYPE STANDARD TABLE,
<DYN_WA>.
"產生 I_IFC 內容的 Work Area & 動態 Table 要建立的欄位
DATA: WA_IFC TYPE LVC_S_FCAT,
I_IFC TYPE LVC_T_FCAT.
"METHOD CL_ALV_TABLE_CREATE=>CREATE_DYNAMIC_TABLE
"回傳的 Table & Line
DATA: DY_TABLE TYPE REF TO DATA,
DY_LINE TYPE REF TO DATA.
設定動態 Table 欄位
"設定要建立的欄位以及型態
WA_IFC-FIELDNAME = 'TEXT'.
WA_IFC-DATATYPE = 'C'.
WA_IFC-INTTYPE = 'C'.
WA_IFC-INTLEN = '50'.
APPEND WA_IFC TO I_IFC. CLEAR WA_IFC.
建立動態 Table 的方法
CALL METHOD CL_ALV_TABLE_CREATE=>CREATE_DYNAMIC_TABLE
EXPORTING
IT_FIELDCATALOG = P_IFC
IMPORTING
EP_TABLE = DY_TABLE.
ASSIGN DY_TABLE->* TO <DYN_TABLE>.
"因為 Dynamic Internal 沒有 Header Line
"所以要建立一個 Work Area 之後接收 or 寫入 Table 的值
CREATE DATA DY_LINE LIKE LINE OF <DYN_TABLE>.
ASSIGN DY_LINE->* TO <DYN_WA>.
建立資料到 Internal Table
注意下面的 Code,因為使用指標,所以無法像一般 Work Area 直接 [WA]-[FIELD NAME],因此需要透過另一個指標,透過 ASSIGN COMPONENT [field] OF STRUCTURE [Structure] TO [指標] 來指向 Work Area 的欄位並填入相關值。
FIELD-SYMBOLS: <FS>.
DATA: FNAME(10) TYPE C.
FNAME = 'TEXT'.
ASSIGN COMPONENT FNAME OF STRUCTURE <DYN_WA> TO <FS>.
<FS> = 'TEXT_VALUE 1'.
APPEND <DYN_WA> TO <DYN_TABLE>.
<FS> = 'TEXT_VALUE 2'.
APPEND <DYN_WA> TO <DYN_TABLE>.
修改 Internal Table
LOOP AT <DYN_TABLE> INTO <DYN_WA>.
ASSIGN COMPONENT FNAME OF STRUCTURE <DYN_WA> TO <FS>.
<FS> = 'TEXT_VALUE MODIFY'.
MODIFY <DYN_TABLE> FROM <DYN_WA>.
ENDLOOP.
刪除 Internal Table
LOOP AT <DYN_TABLE> INTO <DYN_WA>.
IF SY-TABIX = 2.
DELETE <DYN_TABLE> INDEX SY-TABIX.
ENDIF.
ENDLOOP.
SOURCE CODE :
REPORT Z_EX_DYNAMIC_TABLE.
"指標 for 動態 Table 與 Work Area
FIELD-SYMBOLS: <DYN_TABLE> TYPE STANDARD TABLE,
<DYN_WA>.
DATA: WA_IFC TYPE LVC_S_FCAT, "產生 I_IFC 內容的 Work Area
I_IFC TYPE LVC_T_FCAT. "存放動態 Table 要建立的欄位
"METHOD CL_ALV_TABLE_CREATE=>CREATE_DYNAMIC_TABLE 回傳的 Table & Line
DATA: DY_TABLE TYPE REF TO DATA,
DY_LINE TYPE REF TO DATA.
"設定要建立的欄位以及型態
WA_IFC-FIELDNAME = 'TEXT'.
WA_IFC-DATATYPE = 'C'.
WA_IFC-INTTYPE = 'C'.
WA_IFC-INTLEN = '50'.
APPEND WA_IFC TO I_IFC. CLEAR WA_IFC.
CALL METHOD CL_ALV_TABLE_CREATE=>CREATE_DYNAMIC_TABLE
EXPORTING
IT_FIELDCATALOG = I_IFC
IMPORTING
EP_TABLE = DY_TABLE.
ASSIGN DY_TABLE->* TO <DYN_TABLE>.
CREATE DATA DY_LINE LIKE LINE OF <DYN_TABLE>.
ASSIGN DY_LINE->* TO <DYN_WA>.
FIELD-SYMBOLS: <FS>.
DATA: FNAME(10) TYPE C.
FNAME = 'TEXT'.
ASSIGN COMPONENT FNAME OF STRUCTURE <DYN_WA> TO <FS>.
<FS> = 'TEXT_VALUE 1'.
APPEND <DYN_WA> TO <DYN_TABLE>.
<FS> = 'TEXT_VALUE 2'.
APPEND <DYN_WA> TO <DYN_TABLE>.
LOOP AT <DYN_TABLE> INTO <DYN_WA>.
ASSIGN COMPONENT FNAME OF STRUCTURE <DYN_WA> TO <FS>.
<FS> = 'TEXT_VALUE MODIFY'.
MODIFY <DYN_TABLE> FROM <DYN_WA>.
ENDLOOP.
LOOP AT <DYN_TABLE> INTO <DYN_WA>.
IF SY-TABIX = 2.
DELETE <DYN_TABLE> INDEX SY-TABIX.
ENDIF.
ENDLOOP.
沒有留言:
張貼留言