Tuesday, April 14, 2009

Tabelle in CSV-Format umwandeln

Um Tabellen in das CSV-Format umzuwandeln (Zellwerte mit Seperator, z.B.
Semikolon, getrennt), kann der Funktionsbaustein SAP_CONVERT_TO_CSV_FORMAT
verwendet werden.


TYPES ly_text_data(4096) TYPE c.
DATA: lt_datatable TYPE STANDARD TABLE OF ...,
lv_filename TYPE string,
lt_csv TYPE STANDARD TABLE OF ly_text_data,
lv_csv_line TYPE ly_text_data,
lv_errortext TYPE string.

[...]

* Catch system exceptions:
CATCH SYSTEM-EXCEPTIONS
open_dataset_no_authority = 1
dataset_cant_open = 2
dataset_write_error = 3
dataset_cant_close = 4
OTHERS = 99.

* Open dataset:
OPEN DATASET lv_filename FOR OUTPUT IN TEXT MODE
ENCODING DEFAULT "4.7
MESSAGE lv_errortext.

IF sy-subrc <> 0.
IF lv_errortext IS INITIAL.
lv_errortext = 'Error on opening file'. "#EC NOTEXT
ENDIF.

MESSAGE lv_errortext TYPE 'E'.
ENDIF.

* convert result table into csv format
CALL FUNCTION 'SAP_CONVERT_TO_CSV_FORMAT'
TABLES
i_tab_sap_data = lt_datatable
CHANGING
i_tab_converted_data = lt_csv
EXCEPTIONS
conversion_failed = 1
OTHERS = 2.

IF sy-subrc <> 0.
MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.

* Transfer data:
LOOP AT lt_csv INTO lv_csv_line.
TRANSFER lv_csv_line TO lv_filename.
ENDLOOP.

* Close dataset:
CLOSE DATASET lv_filename.
ENDCATCH.

* Check for error:
CASE sy-subrc.
WHEN 1.
MESSAGE 'No authority' TYPE 'E'. "#EC NOTEXT
WHEN 2.
MESSAGE 'Can not open file' TYPE 'E'. "#EC NOTEXT
WHEN 3.
MESSAGE 'File write error' TYPE 'E'. "#EC NOTEXT
WHEN 4.
MESSAGE 'Can not close file' TYPE 'E'. "#EC NOTEXT
WHEN OTHERS.
MESSAGE 'Error on creating file' TYPE 'E'. "#EC NOTEXT
ENDCASE.

No comments: