If you need to download the internal table into an Excel document in ABAP program, you can use the class cl_salv_export_tool_xls
to achieve it. Please check below for the sample code.
report z_gary_test1.
data: gt_t000 like table of t000.
data: gt_fieldcat type lvc_t_fcat,
gs_fieldcat type lvc_s_fcat.
data: gv_length type i.
data: gt_stream type salv_xml_xline_tabtype.
data: gv_filename type string.
data: gr_data type ref to data,
go_tool_xls type ref to cl_salv_export_tool_xls,
go_config type ref to if_salv_export_configuration,
gv_content type cl_salv_export_tool=>y_file_content,
go_exception type ref to cx_salv_export_error.
start-of-selection.
select *
into table gt_t000
from t000.
* Create an instance of the export tool for table a given table gt_t000
get reference of gt_t000 into gr_data.
go_tool_xls = cl_salv_export_tool=>create_for_excel( gr_data ).
* Configure export properties
go_config = go_tool_xls->configuration( ).
* Get fieldcat by ABAP structure
call function 'LVC_FIELDCATALOG_MERGE'
exporting
i_structure_name = 'T000'
i_bypassing_buffer = 'X'
changing
ct_fieldcat = gt_fieldcat[]
exceptions
inconsistent_interface = 1
program_error = 2
others = 3.
if sy-subrc <> 0.
clear gt_fieldcat[].
exit.
endif.
"Complete fieldcatalog
call function 'LVC_FIELDCAT_COMPLETE'
changing
ct_fieldcat = gt_fieldcat[].
loop at gt_fieldcat into gs_fieldcat.
go_config->add_column( header_text = |{ gs_fieldcat-coltext }|
field_name = |{ gs_fieldcat-fieldname }|
display_type = if_salv_export_column_conf=>display_types-text_view ).
endloop.
* Create the excel document
try.
go_tool_xls->read_result(
importing content = gv_content ).
catch cx_salv_export_error into go_exception.
message id go_exception->if_t100_message~t100key-msgid
type 'E'
number go_exception->if_t100_message~t100key-msgno .
endtry.
* Set Filename
gv_filename = 'H:\Downloads\t000.xlsx'.
* Convert to Binary
call function 'SCMS_XSTRING_TO_BINARY'
exporting
buffer = gv_content
importing
output_length = gv_length
tables
binary_tab = gt_stream.
* Download
cl_gui_frontend_services=>gui_download(
exporting
bin_filesize = gv_length
filetype = 'BIN'
filename = gv_filename
changing
data_tab = gt_stream
exceptions
file_write_error = 1
no_batch = 2
gui_refuse_filetransfer = 3
invalid_type = 4
no_authority = 5
unknown_error = 6
header_not_allowed = 7
separator_not_allowed = 8
filesize_not_allowed = 9
header_too_long = 10
dp_error_create = 11
dp_error_send = 12
dp_error_write = 13
unknown_dp_error = 14
access_denied = 15
dp_out_of_memory = 16
disk_full = 17
dp_timeout = 18
file_not_found = 19
dataprovider_exception = 20
control_flush_error = 21
not_supported_by_gui = 22
error_no_gui = 23
others = 24 ).
if sy-subrc <> 0.
message e000(zdev) with 'Fail to download the file' space space space.
else.
message s000(zdev) with 'Download the file successfully' space space space.
endif.