How to Create .csv File

Posted on Apr. 26, 2010 at 12.12 PM - Kuala Lumpur, Malaysia

Sometimes, there is a requirement whereby we need to convert certain data format into other data format, like from fixed length to comma separated (csv) file.

This requirement can be achieved quite easily actually, as SAP has provided many standard functionalities, and class cl_rsda_csv_converter is one of them. Below is the step by step to implement it.

1. Instantiate the class

* Instantiate the class

CALL METHOD cl_rsda_csv_converter=>create

RECEIVING

r_r_conv = lo_converter.

2. Reformat the data

Some data may need reformatting, and this is especially true for amount or quantity fields. So, we need to cast it back to its original value before we can reformat it to the new format. For that purpose, field symbol is very handy.

* Cast the values back to its original condition

ASSIGN <ls_tempse_data>-content TO: <ls_p60_cl> CASTING.

Function module 'HRCM_AMOUNT_TO_STRING_CONVERT' may also be used as necessary.

* Convert value to string

CHECK <ls_p60_cl>-&1 IS ASSIGNED.

CALL FUNCTION 'HRCM_AMOUNT_TO_STRING_CONVERT'

EXPORTING

betrg = <ls_p60_cl>-&1

waers = 'GBP'

* NEW_DECIMAL_SEPARATOR =

* NEW_THOUSANDS_SEPARATOR =

IMPORTING

string = ls_p60data-&1

.

3. Create .csv format using method STRUCTURE_TO_CSV

* Convert structure to csv value

CALL METHOD lo_converter->structure_to_csv

EXPORTING

i_s_data = ls_p60data

IMPORTING

e_data = ls_p60data1.

4. Add CR at the end of the each Record

* As default ASCII mode append a CR/LF after each record

CONCATENATE ls_p60data1 cl_abap_char_utilities=>cr_lf

INTO ls_file_data_asc-line.

APPEND ls_file_data_asc TO lt_file_data_asc.

Once it's created, we can create it as application file using keyword OPEN DATASET or as presentation file using method GUI_DOWNLOAD from class CL_GUI_FRONTEND_SERVICES.

Life is beautiful! Let's make it meaningful and colorful!