ABAP - Create CSV Files Easily Using CL_CSV_FACTORY
Hello Everyone! 👋
Create CSV Files Easily in ABAP Using CL_CSV_FACTORY
In many scenarios, we need to download internal table data in CSV format. Often, the requirements vary for example, using different field separators such as semicolon (;), comma (,). Additionally, we may need to include a header row and format fields like date, time, or timestamp.
All of this can be handled very easily using the CL_CSV_FACTORY class. The best part is that this class is also available in the SAP Public Cloud.
Step 1 – Select the Data
SELECT FROM vbak
FIELDS vbeln, vbtyp, erdat
INTO TABLE @DATA(lt_test)
UP TO 10 ROWS.
Step 2 – Create a Simple CSV with Header
This example generates a CSV using a semicolon as the delimiter and includes the header row automatically.
DATA(lv_xstring_v1) = cl_csv_factory=>new_writer(
)->set_delimiter( ';'
)->set_write_header( abap_true
)->write( REF #( lt_test ) ).
Step 3 – CSV with Custom Headers and Field Formatting
Here we customize the column headers and also format the date field using an ISO date format.
DATA(lv_xstring_v2) = cl_csv_factory=>new_writer(
)->set_delimiter( ';'
)->set_write_header( abap_true
)->write(
itab_ref = REF #( lt_test )
fieldcatalog = VALUE if_csv_field_catalog=>ty_t_fieldcatalog(
( fieldname = 'VBELN' header_text = |Sales Order| )
( fieldname = 'VBTYP' header_text = |Sales Document Type| )
( fieldname = 'ERDAT'
header_text = |Created On|
format = cl_csv_field_format=>date_iso )
) ).
How It Works
- The internal table is passed by reference to the CSV writer.
- The delimiter and header options are configured.
- The field catalog controls column names and formatting.
- The output is returned as an XSTRING.
Comments
Post a Comment