File Handling
Files on the application server (visible in AL11) are processed with dataset statements — works in background jobs:
29.1 Application server files (OPEN DATASET)
Files on the application server (visible in AL11) are processed with dataset statements — works in background jobs:
Modes: TEXT MODE, BINARY MODE, LEGACY TEXT/BINARY MODE; FOR APPENDING, FOR UPDATE. Catch CX_SY_FILE_OPEN, CX_SY_FILE_AUTHORITY, CX_SY_CODEPAGE_CONVERTER_INIT. Use logical file names (transaction FILE, function FILE_GET_NAME) instead of hard-coded paths, and check authority with AUTHORITY_CHECK_DATASET (object S_DATASET).
DATA(lv_file) = `/usr/sap/trans/data/orders.csv`.
" Write
OPEN DATASET lv_file FOR OUTPUT IN TEXT MODE ENCODING UTF-8.
IF sy-subrc <> 0.
MESSAGE |Cannot open { lv_file }| TYPE 'E'.
ENDIF.
LOOP AT lt_orders INTO DATA(ls_o).
TRANSFER |{ ls_o-order_id };{ ls_o-customer };{ ls_o-amount }| TO lv_file.
ENDLOOP.
CLOSE DATASET lv_file.
" Read
DATA lv_line TYPE string.
OPEN DATASET lv_file FOR INPUT IN TEXT MODE ENCODING UTF-8.
DO.
READ DATASET lv_file INTO lv_line.
IF sy-subrc <> 0. EXIT. ENDIF.
SPLIT lv_line AT ';' INTO DATA(lv_id) DATA(lv_cust) DATA(lv_amt).
ENDDO.
CLOSE DATASET lv_file.
DELETE DATASET lv_file. " remove the file29.2 Presentation server files (front end)
Only in dialog (SAP GUI), not in background jobs:
The function modules GUI_UPLOAD / GUI_DOWNLOAD are equivalent older wrappers. Other helpers: file_open_dialog, file_save_dialog, directory_browse.
DATA lt_lines TYPE string_table.
cl_gui_frontend_services=>gui_upload(
EXPORTING filename = p_file
filetype = 'ASC'
CHANGING data_tab = lt_lines
EXCEPTIONS file_open_error = 1 file_read_error = 2 OTHERS = 3 ).
cl_gui_frontend_services=>gui_download(
EXPORTING filename = `C:\temp\orders.txt`
filetype = 'ASC'
CHANGING data_tab = lt_lines
EXCEPTIONS OTHERS = 1 ).29.3 Excel and other formats
XLSX: open-source abap2xlsx (on-premise), or the released XCO XLSX API (XCO_CP_XLSX) in ABAP Cloud.
CSV: build with string templates / concat_lines_of; parse with SPLIT.
XML/JSON: CALL TRANSFORMATION (XSLT or Simple Transformations, id for asXML/asJSON), /UI2/CL_JSON, XCO_CP_JSON, CL_SXML_STRING_WRITER.
CALL TRANSFORMATION id SOURCE orders = lt_orders RESULT XML DATA(lv_xml).
DATA(lo_writer) = cl_sxml_string_writer=>create( type = if_sxml=>co_xt_json ).
CALL TRANSFORMATION id SOURCE orders = lt_orders RESULT XML lo_writer.
DATA(lv_json) = cl_abap_conv_codepage=>create_in( )->convert( lo_writer->get_output( ) ).29.4 Attachments and e-mail
Business Communication Services: CL_BCS (classic) or CL_BCS_MAIL_MESSAGE (released, ABAP Cloud) to send e-mails with attachments (PDF from forms, XLSX). Monitor in SOST.