CSV utility class

*Note* This page links to SAPlink compliant code. If you are unfamiliar with SAPlink, please visit this page.

Background: From time to time, I have had requests to work with custom data in excel and import it in an ABAP program or was asked to export some processed data back into excel, that I decided to write a CSV (Comma Separated Values) utility class that would make my life a little bit easier.

What: My custom SAP class ZCL_CSV (SAPlink nugget)


ZCL_CSV methods list.

How to use: Pass in two parameters and one changing parameter. The two parameters are the CSV file and its defined structure, and the changing parameter is the table you want your data to be put into.

CSV_TO_TABLE parameters

Code Sample:

     IV_CSV = "CSV File as a string.
     IS_CSV = "The structure of the CSV file
     ET_CONVERTED_TABLE = "The table to store the data  ).

Full Code Sample:

 DATA: lv_data type string.

 TYPES: begin of ty_struct,
   comp_foo type string,
   comp_bar type string,
   comp_baz type string,
   end of ty_struct.

 TYPES: begin of ty_struct2,

   comp_bar type string,
   comp_baz type string,
   comp_qux type string,
   end of ty_struct2.

 DATA: ls_struct TYPE ty_struct. "CSV structure
 DATA: lt_struct TYPE TABLE OF ty_struct2. "My table structure

 DATA: lv_filename TYPE string.
 DATA: lv_file_data_string TYPE STRING.

 DATA: lv_file_save TYPE STRING.

 CONCATENATE 'foo,bar,baz' cl_abap_char_utilities=>cr_lf 'foo2,bar2,baz2' INTO lv_data.

 ZCL_CSV=>SHOW_OPEN_DIALOG( CHANGING iv_filename = lv_filename ).

 lv_file_data_string = ZCL_CSV=>GET_FILE( lv_filename ) .

     IV_CSV =  lv_file_data_string
     IS_CSV = ls_struct
     ET_CONVERTED_TABLE = lt_struct   ).

 lt_csv_table = ZCL_CSV=>TABLE_TO_CSV( lt_struct ) .
 lv_file_save = ZCL_CSV=>SHOW_SAVE_DIALOG( ).
 ZCL_CSV=>SAVE_FILE( IV_FILENAME = lv_file_save IV_CSV_TABLE = lt_csv_table ).

Leave a Reply

Your email address will not be published. Required fields are marked *

3 + = six