How to Download Data from Internal Table to an Excel File

This blog post is explaining all about how to download data from internal table to an excel file.

Requirement: On selection screen user will give the input as country name and file name in which user want to download the data to an excel file based on the given country name.

Step 1: Design Selection Screen. On selection screen declare country and file name as parameter.

SELECTION-SCREEN BEGIN OF BLOCK b1 WITH FRAME. PARAMETERS:p_land TYPE kna1-land1, p_file TYPE rlgrap-filename.
SELECTION-SCREEN END OF BLOCK b1.

Step 2: Declare structure, internal table and work area.

TYPES: BEGIN OF ty_kna1, kunnr TYPE kunnr, name1 TYPE name1, land1 TYPE land1, ort01 TYPE ort01, END OF ty_kna1. DATA: it_kna1 TYPE TABLE OF ty_kna1, wa_kna1 TYPE ty_kna1.

Step 3: Declare variables and internal table for heading.

DATA: g_str1 TYPE string VALUE '.xls', g_str TYPE string, g_str2 TYPE string. DATA : BEGIN OF it_header OCCURS 0, line(50) TYPE c, END OF it_header.

Step 4: Use function module KD_GET_FILENAME_ON_F4 for F4 help for file name.

AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file. CALL FUNCTION 'KD_GET_FILENAME_ON_F4' EXPORTING static = 'X' CHANGING file_name = P_file.

Step 5: Append all the heading for each field into internal table.

START-OF-SELECTION. it_header-line = 'Customer Number'. APPEND it_header. it_header-line = 'Customer Name'. APPEND it_header. it_header-line = 'Country'. APPEND it_header. it_header-line = 'City'. APPEND it_header.

Step 6: I want data in excel file so if user did not take F4 help then extension of file needs to append to file name. If user take F4 help and select excel file then no need to append extension.

IF p_file NA '.xls'. g_str = p_file. CONCATENATE g_str g_str1 INTO g_str2. ELSE. g_str2 = p_file. ENDIF.

Step 7: Write Select query to fetch data from database.

SELECT kunnr name1 land1 ort01 FROM kna1 INTO TABLE it_kna1 WHERE land1 = p_land.

Step 8: Call the function module GUI_DOWNLOAD to download the data from the database into excel file.

CALL FUNCTION 'GUI_DOWNLOAD' EXPORTING filename = g_str2 filetype = 'ASC' write_field_separator = 'X' TABLES data_tab = it_kna1 fieldnames = it_header .

Output

Once you execute it file with name Customer excel file will be created and data will be downloaded.

If you want to download data into existing excel file Press F4 for file name.

Then Execute it, you will get data into the selected file.