ABAP读取Excel文件可以使用多种方式实现,最常见的就是使用标准函数进行读取,对于期初导入有很大帮助。常用的标准函数有2个,ALSM_EXCEL_TO_INTERNAL_TABL 和 TEXT_CONVERT_XLS_TO_SAP
文章采用的是ALSM_EXCEL_TO_INTERNAL_TABL对excel进行处理,代码如下:
data :begin of gs_itab , **定义内表从excel获取数据后写入 matnr type mara-matnr, mtart type mara-mtart, matkl type mara-matkl, MEINS type mara-MEINS. end of gs_itab. data : gt_itab like TABLE OF gs_itab . PARAMETERS P_FILE LIKE rlgrap-filename OBLIGATORY. AT SELECTION-SCREEN ON VALUE-REQUEST FOR P_FILE. PERFORM FRM_GET_FILE. START-OF-SELECTION. PERFORM frm_get_excel. FORM FRM_GET_FILE. DATA: lt_filetab TYPE filetable, l_rc TYPE i. CLEAR lt_filetab. REFRESH lt_filetab. CALL METHOD CL_GUI_FRONTEND_SERVICES=>FILE_OPEN_DIALOG EXPORTING window_title = '打开.xls文件' "弹出对话框的抬头 " default_extension = '123.xlsx'"默认的扩展名 " default_filename = '123' "默认的文件名 file_filter = CL_GUI_FRONTEND_SERVICES=>FILETYPE_EXCEL "只显示某中文件类型 * with_encoding = initial_directory = 'd:\text' ""默认打开文件地址 multiselection = abap_FALSE "是否可以选择多个文件 CHANGING file_table = lt_filetab rc = l_rc . IF sy-subrc <> 0. * Implement suitable error handling here ENDIF. CHECK l_rc EQ 1. READ TABLE lt_filetab INDEX 1 INTO P_FILE . ENDFORM. FORM frm_get_excel . CONSTANTS: cns_begin_row TYPE i VALUE 1, "Beginning row of excel file cns_begin_col TYPE i VALUE 1, "Beginning column of excel file cns_end_row TYPE i VALUE 9999, "Ending row of excel file cns_end_col TYPE i VALUE 55 . "Ending column of excel file DATA: BEGIN OF gs_excel. INCLUDE STRUCTURE alsmex_tabline. DATA: END OF gs_excel. DATA: gt_excel like TABLE OF gs_excel. DATA : l_column type i. field-symbols : <fs>. CALL FUNCTION 'ALSM_EXCEL_TO_INTERNAL_TABLE' EXPORTING filename = P_FILE i_begin_col = 1 i_begin_row = 1 i_end_col = 4 i_end_row = 9999 TABLES intern = gt_excel EXCEPTIONS INCONSISTENT_PARAMETERS = 1 UPLOAD_OLE = 2 OTHERS = 3 . IF sy-subrc <> 0. * Implement suitable error handling here ENDIF. SORT gt_excel by row col. loop at gt_excel into gs_excel. MOVE GS_EXCEL-COL TO l_column. ASSIGN COMPONENT l_columN OF STRUCTURE gs_itab to <fs>. MOVE gs_excel-value to <fs>. AT END OF ROW. APPEND GS_ITAB TO GT_ITAB. CLEAR GS_itab. ENDAT. ENDLOOP. ENDFORM.
在使用ALSM_EXCEL_TO_INTERNAL_TABL 需要注意2点 : 一是每个value只能导入前50个字符,二是如果超过9999行,行号会初始化为从零开始.
这是因为函数定义表ALSMEX_TABLINE 做了限定。
如果需要对于取消字符限制,需要对ALSM_EXCEL_TO_INTERNAL_TABL进行改造