Alsm excel to internal table

***************************************************************************************************************

WARNING: This post is intended to Excel upload FM which is now obsolete. Follow this, only if you are working on older systems to maintain the code where you’ve already used ‘ALSM_EXCEL_TO_INTERNAL_TABLE’.

Also this post will help you grasp concept of Field symbols with below application. 

***************************************************************************************************************
This blog post will help you avoid extraneous code every time you create Excel upload program by creating a simple Interface and a structure.

For ALSM_EXCEL_TO_INTERNAL_TABLE, explicitly we need to write code to transfer output of this FM into internal table of desired format. For this we have to map column number of FM output with columns of required internal table using

Refer below example.

CALL FUNCTION ‘ALSM_EXCEL_TO_INTERNAL_TABLE’
EXPORTING
filename            p_file
i_begin_col        1
i_begin_row      1
i_end_col          9
i_end_row        65536
TABLES
intern                  t_file
EXCEPTIONS
inconsistent_parameters 1
upload_ole                      2
OTHERS                        3.

Output is in below format.

Further based on column number, work area is filled using CASE-ENDCASE and then Appending work area into required internal table in AT END OF ROW block.

LOOP

CASE (column)

when 1. wa_itab-col1 = value

when 2. wa_itab-col2 = value.

….and so on depending upon number of columns in Excel

ENDCASE

AT _END OF_ROW

APPEND wa_itab to itab.

END AT

ENDLOOP.

In order to avoid extraneous code when it comes to uploading Excel File with huge number of columns, create a FM with below code. Once you create Z FM, for every Excel File you’ll just need to create a structure in SE11  and you’re good to go.

Pass Desktop File path, Structure name in p_File and STR as input Parameters respectively.

First Create Structure in SE11 similar to the Excel File format.

FUNCTION zxls_into_it_2.
*”———————————————————————-
*”*”Local interface:
*”  IMPORTING
*”     REFERENCE(P_FILE) TYPE  RLGRAP-FILENAME
*”     REFERENCE(HEADER) TYPE  CHAR1 DEFAULT ‘X’
*”     REFERENCE(STR) TYPE  CHAR30
*”  TABLES
*”      IT_XLS_DATA TYPE  STANDARD TABLE
*”———————————————————————-
TYPE-POOLSabap,slis.
FIELD-SYMBOLS:<dy_table> TYPE STANDARD TABLE,
<fs_current_field>,
<wa_str>,<wa_temp>
.
DATA:new_line    TYPE REF TO data,
new_line2 TYPE REF TO data,
li_fieldcat TYPE lvc_t_fcat,
dy_table    TYPE REF TO data,
t_file      TYPE STANDARD TABLE OF alsmex_tabline,
wa_file     TYPE alsmex_tabline,
v_col       TYPE i,
begin_row   TYPE i.

********This will provide Fields in Row format of Structure created(which should be similar to Excel Format).
CALL FUNCTION ‘LVC_FIELDCATALOG_MERGE’
EXPORTING
i_structure_name       str
CHANGING
ct_fieldcat                  li_fieldcat
EXCEPTIONS
inconsistent_interface 1
program_error            2
OTHERS                    3.
IF sysubrc EQ 0.

********This will create internal table which will have fields as per the Excel Format.
CALL METHOD cl_alv_table_create=>create_dynamic_table
EXPORTING
it_fieldcatalog           li_fieldcat
i_length_in_byte          ‘X’
IMPORTING
ep_table                  dy_table
EXCEPTIONS
generate_subpool_dir_full 1
OTHERS                    2.
IF sysubrc EQ 0.
ASSIGN dy_table->TO <dy_table>.
ENDIF.

******V_col will hold the number of Columns inside Excel File which is later passed to ALSM_EXCEL_TO_INTERNAL_TABLE’ .

DESCRIBE TABLE li_fieldcat LINES v_col.

******Logic to skip Header
IF header ‘X’.
begin_row 2.
ELSE.
begin_row 1.
ENDIF.

******Core FM which will provide excel data in  t_file with row/coumn/value format

CALL FUNCTION ‘ALSM_EXCEL_TO_INTERNAL_TABLE’
EXPORTING
filename              p_file
i_begin_col          1
i_begin_row        begin_row
i_end_col            v_col
i_end_row            65536
TABLES
intern                  t_file
EXCEPTIONS
inconsistent_parameters 1
upload_ole              2
OTHERS                  3.

IF sysubrc EQ 0.
LOOP AT t_file INTO wa_file.

******This Block will create new area to store column wise data.<wa_temp> acts as a work area which is completely blank at start of new row
AT NEW row.
CREATE DATA new_line2 LIKE LINE OF <dy_table>.
ASSIGN new_line2->TO <wa_temp>.
ENDAT.

*******for every iteration, wa_file-col will have increment till number of columns in Excel file and then reset to 1 when there’s new row i.e row = 1. (Refer example at end of blog)

ASSIGN COMPONENT wa_filecol OF STRUCTURE <wa_temp> TO <fs_current_field>.
IF sysubrc EQ 0.

<fs_current_field> wa_filevalue.
UNASSIGN <fs_current_field>.
ENDIF.

*****Finally once all Columns are processed and new row is about to start, append the workarea into Internal table

AT END OF row.
APPEND <wa_temp> TO it_xls_data.
UNASSIGN <fs_current_field>.
UNASSIGN <wa_temp>.
ENDAT.

ENDLOOP.
ENDIF.
ENDIF.
ENDFUNCTION.

Explanation with example:

Now simply create a structure in SE11, define Internal table of that type in report and call above FM and pass the structure name and file path and its done.

ABAP программа загрузки данных из EXCEL в SAP систему. Разберу на примере загрузку Excel файла, проверку и преобразование данных, полученных при загрузке ABAP. 
Это полезная и часто используемая задача.

Загрузка данных из Excel

Рассмотрим один из вариантов загрузки данных из Excel на примере программы ABAP. Подробно разберу каждый блок программы для лучшего понимания. Ссылку на файл Excel для тестирования данной программы приведу в конце данной статьи.

Программа ABAP Excel. Загрузка из Excel в SAP

Селекционный экран ABAP для выбора файла

Создаю селекционный экран ABAP на который добавлю одно поле для выбора файла из которого будут загружаться данные.

PARAMETERS p_file TYPE string LOWER CASE.

Селекционный экран ABAP для выбора файла Excel.

Селекционный экран ABAP для выбора файла Excel.

Средство поиска ABAP для файла

Так же в этой части кода добавляю средство поиска ABAP для поля файла через использование события AT SELECTION-SCREEN ON VALUE-REQUEST.

AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file.

  cl_salv_test_data=>select_file( IMPORTING filename = p_file ).

Окно выбора файла стандартный проводник

Окно выбора файла стандартный проводник

Определяю тип для внутренней таблицы результата

Я определил локальный тип структуры результата для большей наглядности в статье, но на его месте может быть и тип ABAP словаря.

START-OF-SELECTION.

  TYPES:

    BEGIN OF ts_data,

      carrid    TYPE s_carr_id,

      connid    TYPE s_conn_id,

      fldate    TYPE s_date,

      price TYPE s_price,

      currency  TYPE s_currcode,

      planetype TYPE s_planetye,

      seatsmax  TYPE s_seatsmax,

      seatsocc  TYPE s_seatsocc,

      gjahr     TYPE gjahr,

      monat     TYPE monat,

    END OF ts_data.

Внутренняя таблица lt_sflight это таблица в которую будет помещён итоговый уже преобразованный результат загрузки. А таблица lt_intern это внутренняя таблица abap в которую изначально будут помещены данные из Excel для дальнейшей обработки.

  DATA:

    lt_sflight TYPE STANDARD TABLE OF ts_data,

    lt_intern  TYPE TABLE OF alsmex_tabline.

Структура ABAP словаря alsmex_tabline

Структура ABAP словаря alsmex_tabline

ФМ ALSM_EXCEL_TO_INTERNAL_TABLE

Сама загрузка происходит при вызове функционального метода ALSM_EXCEL_TO_INTERNAL_TABLE, разберём подробно его параметры:

    CALL FUNCTION ‘ALSM_EXCEL_TO_INTERNAL_TABLE’

      EXPORTING

        filename                = CONV rlgrapfilename( p_file )

        i_begin_col             = 1

        i_begin_row             = 2

        i_end_col               = 10

        i_end_row               = 10000

      TABLES

        intern                  = lt_intern

      EXCEPTIONS

        inconsistent_parameters = 1

        upload_ole              = 2

        OTHERS                  = 3.

  • filename – путь к файлу Excel. Использование конструкции CONV в этом случае преобразует параметр p_file к нужному типу.
  • i_begin_col – номер колонки с которой начинать загрузку
  • i_begin_row – номер строки с которой начинаем загрузку. В нашем случае установил значение 2 так как мне не нужно обрабатывать первую строку заголовка.
  • i_end_col – сколько колонок нам нужно анализировать при загрузке
  • i_end_row – сколько записей максимум берётся для анализа.
  • intern – внутренняя таблица в которую будут загружаться данные из файла.

Обработка результата загрузки данных из Excel

С использованием конструкции нового синтаксиса LOOP AT GROUP BY обходим таблицу сгруппировав её по столбцу row, в котором расположен номер строки. И после обработки всей группы с одинаковым номером строки мы добавляем запись в таблицу результата и переходим к следующей группе.

Более подробно загрузка и обработка данных после разбирается в видео и не забывайте подписаться на мой канал YouCoder.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

      LOOP AT lt_intern INTO DATA(ls_intern)

        GROUP BY ( row = ls_internrow )

        REFERENCE INTO DATA(lr_grp).

        DATA(ls_alv) = VALUE ts_data( ).

        LOOP AT GROUP lr_grp REFERENCE INTO DATA(lr_item).

          CHECK lr_item>value IS NOT INITIAL.

          CASE lr_item>col.

            WHEN 1.

              ls_alvcarrid = lr_item>value.

            WHEN 2.

              ls_alvconnid = lr_item>value.

            WHEN 3.

              ls_alvfldate = |{ lr_item>value+6(4) }{ lr_item>value+3(2) }{ lr_item>value(2) }|. » 29.04.2015 20150429

            WHEN 4.

              lr_item>value = replace( val = lr_item>value regex =‘[,]’ with = ‘.’ occ = 0 ). » 427,94

              ls_alvprice = lr_item>value.

            WHEN 5.

              ls_alvcurrency = lr_item>value.

            WHEN 6.

              ls_alvplanetype = lr_item>value.

            WHEN 7.

              ls_alvseatsmax = lr_item>value.

            WHEN 8.

              IF strlen( lr_item>value ) > 10.

                ls_alvseatsocc = lr_item>value.

              ENDIF.

            WHEN 9.

              IF lr_item>value CO |0123456789| AND lr_item>value >= 1 AND lr_item>value <= 9999.

                ls_alvgjahr = lr_item>value.

              ENDIF.

            WHEN 10.

              IF lr_item>value CO |0123456789| AND lr_item>value >= 1 AND lr_item>value <= 12 .

                ls_alvmonat = lr_item>value.

              ENDIF.

            WHEN OTHERS.

              CONTINUE.

          ENDCASE.

        ENDLOOP.

        APPEND ls_alv TO lt_sflight.

      ENDLOOP.

Конструкции языка ABAP используемые в коде выше:
  • replace – замена символа в строке ABAP
  • strlen – длина строки ABAP
  • LOOP AT GROUP – группировка в цикле ABAP
Быстрый вывод внутренней таблицы ABAP на экран для тестирования:

cl_demo_output=>display( lt_sflight ).

Шаблон программы ABAP загрузки данных из Excel.

Ниже привёл полный код программы загрузки для удобства копирования и тестирования:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

START-OF-SELECTION.

  TYPES:

    BEGIN OF ts_data,

      carrid    TYPE s_carr_id,

      connid    TYPE s_conn_id,

      fldate    TYPE s_date,

      price     TYPE s_price,

      currency  TYPE s_currcode,

      planetype TYPE s_planetye,

      seatsmax  TYPE s_seatsmax,

      seatsocc  TYPE s_seatsocc,

      gjahr     TYPE gjahr,

      monat     TYPE monat,

    END OF ts_data.

  DATA:

    lt_sflight TYPE STANDARD TABLE OF ts_data,

    lt_intern  TYPE TABLE OF alsmex_tabline.

  IF p_file IS NOT INITIAL.

    CALL FUNCTION ‘ALSM_EXCEL_TO_INTERNAL_TABLE’

      EXPORTING

        filename                = CONV rlgrapfilename( p_file )

        i_begin_col             = 1

        i_begin_row             = 2

        i_end_col               = 10

        i_end_row               = 10000

      TABLES

        intern                  = lt_intern

      EXCEPTIONS

        inconsistent_parameters = 1

        upload_ole              = 2

        OTHERS                  = 3.

    IF sysubrc = 0.

      LOOP AT lt_intern INTO DATA(ls_intern)

        GROUP BY ( row = ls_internrow )

        REFERENCE INTO DATA(lr_grp).

        DATA(ls_alv) = VALUE ts_data( ).

        LOOP AT GROUP lr_grp REFERENCE INTO DATA(lr_item).

          CHECK lr_item>value IS NOT INITIAL.

          CASE lr_item>col.

            WHEN 1.

              ls_alvcarrid = lr_item>value.

            WHEN 2.

              ls_alvconnid = lr_item>value.

            WHEN 3.

              ls_alvfldate = |{ lr_item>value+6(4) }{ lr_item>value+3(2) }{ lr_item>value(2) }|. » 29.04.2015 20150429

            WHEN 4.

              lr_item>value = replace( val = lr_item>value regex =‘[,]’ with = ‘.’ occ = 0 ). » 427,94

              ls_alvprice = lr_item>value.

            WHEN 5.

              ls_alvcurrency = lr_item>value.

            WHEN 6.

              ls_alvplanetype = lr_item>value.

            WHEN 7.

              ls_alvseatsmax = lr_item>value.

            WHEN 8.

              IF strlen( lr_item>value ) > 10.

                ls_alvseatsocc = lr_item>value.

              ENDIF.

            WHEN 9.

              IF lr_item>value CO |0123456789| AND lr_item>value >= 1 AND lr_item>value <= 9999.

                ls_alvgjahr = lr_item>value.

              ENDIF.

            WHEN 10.

              IF lr_item>value CO |0123456789| AND lr_item>value >= 1 AND lr_item>value <= 12 .

                ls_alvmonat = lr_item>value.

              ENDIF.

            WHEN OTHERS.

              CONTINUE.

          ENDCASE.

        ENDLOOP.

        APPEND ls_alv TO lt_sflight.

      ENDLOOP.

    ENDIF.

    cl_demo_output=>display( lt_sflight ).

  ENDIF.

Если статья оказалась Вам полезна поддержите проект. Спасибо!

Сайт ABAP программирование YouCoder – это сборник статей и видео о языке программирования ABAP и работе в SAP системе. Есть как уроки abap для начинающих так и новый синтаксис в ABAP и SAP обучение для консультантов SAP.

С некоторых пор MS (чтоб БГ пусто было) решила таки при сохранении XLS в текстовый файл использовать настройки разделителей, чего раньше не наблюдалось. Модуль пришлось изменить и написать еще один для получения параметров Excel:

FUNCTION Z_EXCEL_LOAD.
*»———————————————————————-
*»*»Локальный интерфейс:
*»  IMPORTING
*»     VALUE(FILE_NAME) TYPE  RLGRAP-FILENAME
*»     VALUE(SHEET_NAME) TYPE  CHAR30 OPTIONAL
*»     VALUE(HEADER_ROW) TYPE  SY-TABIX DEFAULT 1
*»     VALUE(DECIMAL_SEPARATOR) TYPE  CHAR1 DEFAULT »
*»     VALUE(DATE_SEPARATOR) TYPE  CHAR1 DEFAULT »
*»     VALUE(DATE_FORMAT) TYPE  CHAR10 DEFAULT »
*»  TABLES
*»      IT_DATA
*»  EXCEPTIONS
*»      ERROR
*»———————————————————————-

  Data:
    Char_Tab,
    X_Tab type X value ’09’,
    App type OLE2_OBJECT,
    Wbs type OLE2_OBJECT,
    Wbk type OLE2_OBJECT,
    Wsh type OLE2_OBJECT,
    FileTxt type RLGRAP-FILENAME,
    it_StringData type standard table of String
      with header line,
    it_Header type standard table of String
      with header line,
    it_Line type standard table of String
      with header line,
    TempDir    type RLGRAP-FILENAME,
    Type_Fld,
    NextRow type sy-tabix,
    Error type sy-subrc,
    Begin of Excel_Parameters,
     DECIMAL_SEPARATOR,
     DATE_SEPARATOR,
     DATE_FORMAT(10),
    End of Excel_Parameters,
    Date1(4),
    Date2(4),
    Date3(4),
    OLE_subrc type sy-subrc,
    CHAR_A value ‘A’,
    CHAR_B value ‘B’.

  Field-symbols:
    <Fld>,
    <Day>,
    <Month>,
    <Year>.
  Field-symbols:
    <X>, <EI>.

*  Assign Char_Tab to <Fld> type ‘X’.
*  <Fld> = X_Tab.

  Assign CHAR_A to <X>  type ‘X’.
  Assign CHAR_B to <EI> type ‘X’.
  <EI> = <EI> — <X>.
  Assign CHAR_TAB to <X> type ‘X’.
  Clear <X>.
  <X> = X_TAB * <EI>.

  CALL FUNCTION ‘GUI_GET_DESKTOP_INFO’
    EXPORTING
      TYPE   = 4  «TmpDir
    CHANGING
      RETURN = TempDir.

  Concatenate TempDir » sy-repid ‘-‘ sy-TIMLO ‘.txt’
    into FileTxt.

  Create object App ‘Excel.Application’.
  Set property of App ‘DisplayAlerts’ = 0.
  Call method of App ‘Workbooks’ = Wbs.
  Call method of Wbs ‘Open’
    EXPORTING
      #1 = File_Name.
  Call method of App ‘ActiveWorkbook’ = Wbk.
  If not SHEET_NAME is initial.
    Call method of Wbk ‘WorkSheets’ = Wsh
      EXPORTING
        #1 = SHEET_NAME.
    Call method of Wsh ‘Select’.
  EndIf.
  Call method of Wbk ‘SaveAs’
    EXPORTING
      #1  = FileTxt
      #2  = -4158 «xlText
      #3  = »
      #4  = »
      #5  = 0
      #6  = 0
      #7  = 0
      #8  = 0
      #9  = 0
      #10 = 0
      #11 = 0
      #12 = 1.
  Call method of App ‘Quit’.
  OLE_subrc = sy-subrc.

  Free object: Wsh, Wbk, Wbs, App.

  If OLE_subrc = 0.
    Data: FileStr type string.
    FileStr = FileTxt.
    Call function ‘GUI_UPLOAD’
      EXPORTING
        FILENAME = FileStr
      TABLES
        DATA_TAB = it_StringData
      EXCEPTIONS
        OTHERS   = 17.

    If sy-subrc = 0.
      Call function ‘ZGET_EXCEL_PARAMETERS’
        IMPORTING
          DECIMAL_SEPARATOR = Excel_Parameters-DECIMAL_SEPARATOR
          DATE_SEPARATOR    = Excel_Parameters-DATE_SEPARATOR
          DATE_FORMAT       = Excel_Parameters-DATE_FORMAT.

      If DECIMAL_SEPARATOR is initial.
        DECIMAL_SEPARATOR = Excel_Parameters-DECIMAL_SEPARATOR.
      EndIf.

      If DATE_SEPARATOR is initial.
        DATE_SEPARATOR = Excel_Parameters-DATE_SEPARATOR.
      EndIf.

      If DATE_FORMAT is initial.
        DATE_FORMAT = Excel_Parameters-DATE_FORMAT.
      EndIf.

      Translate DATE_FORMAT to upper case.
      Split DATE_FORMAT at DATE_SEPARATOR into Date1 Date2 Date3.
      Case ‘DD’.
        when Date1(2).
          Assign Date1 to <Day>.
        when Date2(2).
          Assign Date2 to <Day>.
        when Date3(2).
          Assign Date3 to <Day>.
      EndCase.

      Case ‘MM’.
        when Date1(2).
          Assign Date1 to <Month>.
        when Date2(2).
          Assign Date2 to <Month>.
        when Date3(2).
          Assign Date3 to <Month>.
      EndCase.

      Case ‘YY’.
        when Date1(2).
          Assign Date1 to <Year>.
        when Date2(2).
          Assign Date2 to <Year>.
        when Date3(2).
          Assign Date3 to <Year>.
      EndCase.

      Read table it_StringData index HEADER_ROW.
      If sy-subrc = 0.
        Split it_StringData at Char_Tab into table it_Header.

        NextRow = HEADER_ROW + 1.
        Loop at it_StringData from NextRow.
          Split it_StringData at Char_Tab into table it_Line.

          Clear it_Data.
          Loop at it_Header.
            Assign component it_Header of structure it_Data to <Fld>.
            If sy-subrc = 0.
              Read table it_Line index sy-tabix.
              If sy-subrc = 0.
                Describe field <Fld> type Type_Fld.
                Case Type_Fld.
                  when ‘D’.
                    Data: Day(2), Month(2), Year(4).
                    Split it_Line at DATE_SEPARATOR into Date1 Date2 Date3.

                    If <Year> < 1900.
                      If <Year> > 53.
                        Concatenate ’19’ <Year> into <Year>.
                      Else.
                        Concatenate ’20’ <Year> into <Year>.
                      EndIf.
                    EndIf.

                    <Fld>(4)   = <Year>.
                    <Fld>+4(2) = <Month>.
                    <Fld>+6(2) = <Day>.
                  when ‘P’.
                    Replace DECIMAL_SEPARATOR with ‘.’ into it_Line.
                    <Fld> = it_Line.
                  when others.
                    Perform PrepareString using it_Line.
                    <Fld> = it_Line.
                EndCase.
              EndIf.
            EndIf.
          EndLoop.
          If not it_Data is initial.
            Append it_Data.
          EndIf.
        EndLoop.
      Else.
        Error = 2.
      EndIf.
    Else.
      Error = 1.
    EndIf.
  Else.
    Error = 1.
  EndIf.

  Call function ‘GUI_DELETE_FILE’
    EXPORTING
      FILE_NAME = FileTxt
    EXCEPTIONS
      others    = 1.

  If Error <> 0.
    Raise Error.
  EndIf.

ENDFUNCTION.

FUNCTION ZGET_EXCEL_PARAMETERS.
*»———————————————————————-
*»*»Локальный интерфейс:
*»  EXPORTING
*»     REFERENCE(DECIMAL_SEPARATOR) TYPE  CHAR1
*»     REFERENCE(DATE_SEPARATOR) TYPE  CHAR1
*»     REFERENCE(DATE_FORMAT)
*»———————————————————————-

  Perform AssignCharX.

  PERFORM GET_EXCEL_DECIMAL_SEPARATOR
    USING DECIMAL_SEPARATOR.

  Perform GET_SYSTEM_DATE_SEPARATOR
    USING DATE_SEPARATOR.

  Perform GET_SYSTEM_DATE_FORMAT
    USING DATE_FORMAT.

ENDFUNCTION.

Constants:
  X_TAB(1) TYPE X VALUE ’09’,
  X_0D(1)  TYPE X VALUE ‘0D’,
  X_0A(1)  TYPE X VALUE ‘0A’.

DATA:
  CHAR_TAB type C,
  CHAR_0D  TYPE C,
  CHAR_0A  TYPE C,

  DECIMAL_POINT.

FORM AssignCharX .
  Data: L type i,
        CHAR_A value ‘A’,
        CHAR_B value ‘B’.
  Field-symbols:
    <X>, <EI>.

  Assign CHAR_A to <X>  type ‘X’.
  Assign CHAR_B to <EI> type ‘X’.
  <EI> = <EI> — <X>.

  Assign CHAR_TAB to <X> type ‘X’.
  Clear <X>.
  <X> = X_TAB * <EI>.
  Assign CHAR_0D to <X> type ‘X’.
  Clear <X>.
  <X> = X_0D * <EI>.
  Assign CHAR_0A to <X> type ‘X’.
  Clear <X>.
  <X> = X_0A * <EI>.
ENDFORM.                    » AssignCharX

FORM GET_EXCEL_DECIMAL_SEPARATOR
  USING RESULT.

  DATA:
    APP TYPE OLE2_OBJECT,
    USESYSTEMSEPARATORS(10).

  CREATE OBJECT APP ‘Excel.Application’.
  IF SY-SUBRC = 0.
    GET PROPERTY OF APP
      ‘UseSystemSeparators’ = USESYSTEMSEPARATORS.
    CALL FUNCTION ‘FLUSH’.

    IF SY-SUBRC <> 0 OR
     ( SY-SUBRC = 0 AND USESYSTEMSEPARATORS <> 0 ).

      PERFORM GET_SYSTEM_DECIMAL_SEPARATOR
        USING RESULT.
    ELSE.
      GET PROPERTY OF APP
        ‘DecimalSeparator’ = RESULT.
      CALL FUNCTION ‘FLUSH’.
    ENDIF.

    FREE OBJECT APP.
    CALL FUNCTION ‘FLUSH’.
  ENDIF.
ENDFORM.                    «GET_EXCEL_DECIMAL_SEPARATOR

FORM GET_SYSTEM_DECIMAL_SEPARATOR
  USING RESULT.

  DATA:
    HKEY_CURRENT_USER TYPE I VALUE 1.

  CALL FUNCTION ‘GUI_GET_REGVALUE’
    EXPORTING
      ROOT           = HKEY_CURRENT_USER
      KEY            = ‘Control PanelInternational’
      VALUE_NAME     = ‘sDecimal’
    CHANGING
      STRING         = RESULT
    EXCEPTIONS
      REGISTRY_ERROR = 1.
ENDFORM.                    «GET_SYSTEM_DECIMAL_SEPARATOR

FORM GET_SYSTEM_DATE_SEPARATOR
  USING RESULT.

  DATA:
    HKEY_CURRENT_USER TYPE I VALUE 1.

  CALL FUNCTION ‘GUI_GET_REGVALUE’
    EXPORTING
      ROOT           = HKEY_CURRENT_USER
      KEY            = ‘Control PanelInternational’
      VALUE_NAME     = ‘sDate’
    CHANGING
      STRING         = RESULT
    EXCEPTIONS
      REGISTRY_ERROR = 1.
ENDFORM.                    «GET_SYSTEM_DATE_SEPARATOR

FORM GET_SYSTEM_DATE_FORMAT
  USING RESULT.

  DATA:
    HKEY_CURRENT_USER TYPE I VALUE 1.

  CALL FUNCTION ‘GUI_GET_REGVALUE’
    EXPORTING
      ROOT           = HKEY_CURRENT_USER
      KEY            = ‘Control PanelInternational’
      VALUE_NAME     = ‘sShortDate’
    CHANGING
      STRING         = RESULT
    EXCEPTIONS
      REGISTRY_ERROR = 1.
ENDFORM.                    «GET_SYSTEM_DATE_FORMAT

By
| Last Updated on April 22, 2013
| 42,825

Current Poll

Loading ... Loading …

Many times, we would need to upload data from the Excel File. FM ALSM_EXCEL_TO_INTERNAL_TABLE is useful but has few limitation.

FM ALSM_EXCEL_TO_INTERNAL_TABLE can only load up to 9999 rows from Excel file. This simple utility class would overcome this limitation.

Utility class to Upload Excel file

 
*
CLASS lcl_excel_uploader DEFINITION.
  PUBLIC SECTION.
    DATA: header_rows_count TYPE i.
    DATA: max_rows          TYPE i.
    DATA: filename          TYPE localfile.
    METHODS:
      constructor.
    METHODS:
      upload CHANGING ct_data TYPE ANY TABLE.
  PRIVATE SECTION.
    DATA: lv_tot_components TYPE i.
    METHODS:
      do_upload
        IMPORTING
          iv_begin TYPE i
          iv_end   TYPE i
        EXPORTING
          rv_empty TYPE flag
        CHANGING
          ct_data  TYPE STANDARD TABLE.
 
ENDCLASS.                    "lcl_excel_uploader DEFINITION
 
*
CLASS lcl_excel_uploader IMPLEMENTATION.
  METHOD constructor.
    max_rows = 9999.
  ENDMETHOD.                    "constructor
  METHOD upload.
    DATA: lo_struct   TYPE REF TO cl_abap_structdescr,
          lo_table    TYPE REF TO cl_abap_tabledescr,
          lt_comp     TYPE cl_abap_structdescr=>component_table.
 
    lo_table ?= cl_abap_structdescr=>describe_by_data( ct_data ).
    lo_struct ?= lo_table->get_table_line_type( ).
    lt_comp    = lo_struct->get_components( ).
*
    lv_tot_components = LINES( lt_comp ).
*
    DATA: lv_empty TYPE flag,
          lv_begin TYPE i,
          lv_end   TYPE i.
*
    lv_begin = header_rows_count + 1.
    lv_end   = max_rows.
    WHILE lv_empty IS INITIAL.
      do_upload(
        EXPORTING
            iv_begin = lv_begin
            iv_end   = lv_end
        IMPORTING
            rv_empty = lv_empty
        CHANGING
            ct_data  = ct_data
      ).
      lv_begin = lv_end + 1.
      lv_end   = lv_begin + max_rows.
    ENDWHILE.
  ENDMETHOD.                    "upload
* 
  METHOD do_upload.
 
    DATA: li_exceldata  TYPE STANDARD TABLE OF alsmex_tabline.
    DATA: ls_exceldata  LIKE LINE OF li_exceldata.
    DATA: lv_tot_rows   TYPE i.
    DATA: lv_packet     TYPE i.
    FIELD-SYMBOLS: <struc> TYPE ANY,
                   <field> TYPE ANY.
 
*   Upload this packet
    CALL FUNCTION 'ALSM_EXCEL_TO_INTERNAL_TABLE'
      EXPORTING
        filename                = filename
        i_begin_col             = 1
        i_begin_row             = iv_begin
        i_end_col               = lv_tot_components
        i_end_row               = iv_end
      TABLES
        intern                  = li_exceldata
      EXCEPTIONS
        inconsistent_parameters = 1
        upload_ole              = 2
        OTHERS                  = 3.
*   something wrong, exit
    IF sy-subrc <> 0.
      MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
              WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
      rv_empty = 'X'.
      EXIT.
    ENDIF.
 
*   No rows uploaded, exit
    IF li_exceldata IS INITIAL.
      rv_empty = 'X'.
      EXIT.
    ENDIF.
 
*   Move from Row, Col to Flat Structure
    LOOP AT li_exceldata INTO ls_exceldata.
      " Append new row
      AT NEW row.
        APPEND INITIAL LINE TO ct_data ASSIGNING <struc>.
      ENDAT.
 
      " component and its value
      ASSIGN COMPONENT ls_exceldata-col OF STRUCTURE <struc> TO <field>.
      IF sy-subrc EQ 0.
        <field> = ls_exceldata-value.
      ENDIF.
 
      " add the row count
      AT END OF row.
        IF <struc> IS NOT INITIAL.
          lv_tot_rows = lv_tot_rows + 1.
        ENDIF.
      ENDAT.
    ENDLOOP.
 
*   packet has more rows than uploaded rows,
*   no more packet left. Thus exit
    lv_packet = iv_end - iv_begin.
    IF lv_tot_rows LT lv_packet.
      rv_empty = 'X'.
    ENDIF.
 
  ENDMETHOD.                    "do_upload
ENDCLASS.                    "lcl_excel_uploader IMPLEMENTATION
*
 

To use this utility class..

Demo to use Utility class

 
TYPES:
  BEGIN OF ty_data,
    f1 TYPE char10,
    f2 TYPE char12,
    f3 TYPE matnr,
  END   OF ty_data.
TYPES: tt_data TYPE STANDARD TABLE OF ty_data.
DATA:  t_data  TYPE tt_data.
*
START-OF-SELECTION.
  DATA: lo_uploader TYPE REF TO lcl_excel_uploader.
  CREATE OBJECT lo_uploader.
  lo_uploader->max_rows = 10.
  lo_uploader->filename = 'C:temp123.xls'.
  lo_uploader->header_rows_count = 1.
  lo_uploader->upload( CHANGING ct_data = t_data ).
 
 

Do you have a Code Snippet which you want to share, Submit Code Snippet here

Share It!

ALSM_EXCEL_TO_INTERNAL_TABLE is a standard alsm excel to internal table SAP function module available within SAP R/3 or S/4 Hana systems, depending on your version and release level. It is used to perform a specific ABAP function and below is the pattern details, showing its interface including any import and export parameters, exceptions etc. there is also a full «cut and paste» ABAP pattern code example, along with implementation ABAP coding, documentation and contribution comments specific to this or related objects.

See here to view full function module documentation and code listing for alsm excel to internal table FM, simply by entering the name ALSM_EXCEL_TO_INTERNAL_TABLE into the relevant SAP transaction such as SE37 or SE38.

Function Group: ALSMEX
Program Name: SAPLALSMEX
Main Program:
Appliation area: K
Release date: N/A
Mode(Normal, Remote etc): Normal Function Module
Update:

Function ALSM_EXCEL_TO_INTERNAL_TABLE pattern details

In-order to call this FM within your sap programs, simply using the below ABAP pattern details to trigger the function call…or see the full ABAP code listing at the end of this article. You can simply cut and paste this code into your ABAP progrom as it is, including variable declarations.

CALL FUNCTION 'ALSM_EXCEL_TO_INTERNAL_TABLE'"
EXPORTING
FILENAME = "
I_BEGIN_COL = "
I_BEGIN_ROW = "
I_END_COL = "
I_END_ROW = "

TABLES
INTERN = "

EXCEPTIONS
INCONSISTENT_PARAMETERS = 1 UPLOAD_OLE = 2

.

IMPORTING Parameters details for ALSM_EXCEL_TO_INTERNAL_TABLE

FILENAME —

Data type: RLGRAP-FILENAME
Optional: No
Call by Reference: No ( called with pass by value option)

I_BEGIN_COL —

Data type: I
Optional: No
Call by Reference: No ( called with pass by value option)

I_BEGIN_ROW —

Data type: I
Optional: No
Call by Reference: No ( called with pass by value option)

I_END_COL —

Data type: I
Optional: No
Call by Reference: No ( called with pass by value option)

I_END_ROW —

Data type: I
Optional: No
Call by Reference: No ( called with pass by value option)

TABLES Parameters details for ALSM_EXCEL_TO_INTERNAL_TABLE

INTERN —

Data type: ALSMEX_TABLINE
Optional: No
Call by Reference: Yes

EXCEPTIONS details

INCONSISTENT_PARAMETERS —

Data type:
Optional: No
Call by Reference: No ( called with pass by value option)

UPLOAD_OLE —

Data type:
Optional: No
Call by Reference: No ( called with pass by value option)

Copy and paste ABAP code example for ALSM_EXCEL_TO_INTERNAL_TABLE Function Module

The ABAP code below is a full code listing to execute function module POPUP_TO_CONFIRM including all data declarations. The code uses the original data declarations rather than the latest in-line data DECLARATION SYNTAX but I have included an ABAP code snippet at the end to show how declarations would look using the newer method of declaring data variables on the fly. This will allow you to compare and fully understand the new inline method. Please note some of the newer syntax such as the @DATA is not available until a later 4.70 service pack (SP8), which i why i have stuck to the origianl for this example.

DATA:
lt_intern  TYPE STANDARD TABLE OF ALSMEX_TABLINE, »   
lv_filename  TYPE RLGRAP-FILENAME, »   
lv_inconsistent_parameters  TYPE RLGRAP, »   
lv_upload_ole  TYPE RLGRAP, »   
lv_i_begin_col  TYPE I, »   
lv_i_begin_row  TYPE I, »   
lv_i_end_col  TYPE I, »   
lv_i_end_row  TYPE I. »   

  CALL FUNCTION ‘ALSM_EXCEL_TO_INTERNAL_TABLE’  «

    EXPORTING
         FILENAME = lv_filename
         I_BEGIN_COL = lv_i_begin_col
         I_BEGIN_ROW = lv_i_begin_row
         I_END_COL = lv_i_end_col
         I_END_ROW = lv_i_end_row
    TABLES
         INTERN = lt_intern
    EXCEPTIONS
         INCONSISTENT_PARAMETERS = 1
         UPLOAD_OLE = 2
. » ALSM_EXCEL_TO_INTERNAL_TABLE

ABAP code using 7.40 inline data declarations to call FM ALSM_EXCEL_TO_INTERNAL_TABLE

The below ABAP code uses the newer in-line data declarations. This allows you to see the coding differences/benefits of the later inline syntax. Please note some of the newer syntax below, such as the @DATA is not available until 4.70 EHP 8.

 
«SELECT single FILENAME FROM RLGRAP INTO @DATA(ld_filename).
 
 
 
 
 
 
 

data loading…

related articles:http://www.cnblogs.com/caizjian/archive/2013/04/12/3016284.html

FM: ALSM_EXCEL_TO_INTERNAL_TABLE is a function for uploading Excel files, but this function has two limitations.

One is that each CELL can only import the first 50 characters, and the second is that if it exceeds 9999 lines, the line number will be initialized to start from zero

In fact, the solution is very simple, just change the field of the structure ALSMEX_TABLINE, and then COPY ALSM_EXCEL_TO_INTERNAL_TABLE to ZALSM_EXCEL_TO_INTERNAL_TABLE, and make a few changes.

In addition, if you want to upload Excel with open password protection, just modify the OLE OPEN statement.

And import the specified Sheet, etc. .

The accepted internal table of this function is an internal table of type ALSMEX_TABLINE, which only has three fields of row and column and values. If the value of excel is passed to this internal table, we need to loop to process it to the desired internal table.

Sample display:

DATA:lt_excel TYPE TABLE OF ALSMEX_TABLINE.
DATA ls_excel LIKE LINE OF lt_excel.
FIELD-SYMBOLS:<fs>.
CONSTANTS: gc_begin_row TYPE i VALUE 1,
"Beginning row of excel file
           gc_begin_col TYPE i VALUE 1,
           "Beginning column of excel file
           gc_end_row   TYPE i VALUE 999,
           "Ending row of excel file
           gc_end_col   TYPE i VALUE 999.
           "Ending column of excel file
CALL FUNCTION 'ALSM_EXCEL_TO_INTERNAL_TABLE'
  EXPORTING
    filename                      = p_file
    i_begin_col                   = gc_begin_row
    i_begin_row                   = gc_begin_col
    i_end_col                     = gc_end_row
    i_end_row                     = gc_end_col
  TABLES
    intern                        = lt_excel
* EXCEPTIONS
*   INCONSISTENT_PARAMETERS       = 1
*   UPLOAD_OLE                    = 2
*   OTHERS                        = 3
          .
IF sy-subrc <> 0.
* Implement suitable error handling here
ENDIF.
LOOP AT lt_excel INTO ls_excel.
  IF  ls_excel-col = 1.
            CALL FUNCTION 'CONVERSION_EXIT_MATN1_INPUT'         "Material code plus leading 0.
          EXPORTING
            input        = ls_excel-value
          IMPORTING
            output       = ls_excel-value
          EXCEPTIONS
            length_error = 1
            OTHERS       = 2.
  ENDIF.

  ASSIGN COMPONENT ls_excel-col OF STRUCTURE  gs_tab to <fs>. Assign the fields in the work area gs_tab to the field symbol, and the fields in the work area gs_tab depend on the column ls_excel- in the inner tablecol
  CONDENSE ls_excel-value.                  "  Remove spaces
  <fs> = ls_excel-value.
  at end of row.                                    "If it is the last line, save the workspace gs_tab to the internal table gt_tab
        "gs_tab-row = ls_excel-row.
        APPEND gs_tab TO gt_tab.
        CLEAR: gs_tab.

      ENDAT.

ENDLOOP.

ABAP code for uploading an Excel document into an internal table using function module ALSM_EXCEL_TO_INTERNAL_TABLE.
See code below for structures. The code is base on uploading a simple Excel spreadsheet.
This code also works with the new MS excel format .xlsx. Be carefull though for some reason SAP have decided to use a table structure which
only allows a length of 50 characters per cell of your spreadsheet.

*&---------------------------------------------------------------------*
*& Report  UPLOAD_EXCEL                                                *
*&---------------------------------------------------------------------*
*& Upload and excel file into an internal table using the following    *
*& function module: ALSM_EXCEL_TO_INTERNAL_TABLE                       *
*&---------------------------------------------------------------------*
REPORT  UPLOAD_EXCEL no standard page heading.
*Data Declaration
*----------------
data: itab like alsmex_tabline occurs 0 with header line.
* Has the following format:
*             Row number   | Colum Number   |   Value
*             ---------------------------------------
*      i.e.     1                 1             Name1
*               2                 1             Joe
TYPES: Begin of t_record,
    name1 like itab-value,
    name2 like itab-value,
    age   like itab-value,
    End of t_record.
DATA: it_record type standard table of t_record initial size 0,
      wa_record type t_record.
DATA: gd_currentrow type i.
*Selection Screen Declaration
*----------------------------
PARAMETER p_infile like rlgrap-filename.
************************************************************************
*START OF SELECTION
 call function 'ALSM_EXCEL_TO_INTERNAL_TABLE'
       exporting
            filename                = p_infile
            i_begin_col             = '1'
            i_begin_row             = '2'  "Do not require headings
            i_end_col               = '14'
            i_end_row               = '31'
       tables
            intern                  = itab
       exceptions
            inconsistent_parameters = 1
            upload_ole              = 2
            others                  = 3.
  if sy-subrc <> 0.
    message e010(zz) with text-001. "Problem uploading Excel Spreadsheet
  endif.
* Sort table by rows and colums
  sort itab by row col.
* Get first row retrieved
  read table itab index 1.
* Set first row retrieved to current row
  gd_currentrow = itab-row.
  loop at itab.
*   Reset values for next row
    if itab-row ne gd_currentrow.
      append wa_record to it_record.
      clear wa_record.
      gd_currentrow = itab-row.
    endif.
    case itab-col.
      when '0001'.                              "First name
        wa_record-name1 = itab-value.
      when '0002'.                              "Surname
        wa_record-name2 = itab-value.
      when '0003'.                              "Age
        wa_record-age   = itab-value.
    endcase.
  endloop.
  append wa_record to it_record.
*!! Excel data is now contained within the internal table IT_RECORD
* Display report data for illustration purposes
  loop at it_record into wa_record.
    write:/     sy-vline,
           (10) wa_record-name1, sy-vline,
           (10) wa_record-name2, sy-vline,
           (10) wa_record-age, sy-vline.
  endloop.

Потому что «ALSM_EXCEL_TO_INTERNAL_TABLE» ограничивает общее количество импортируемых строк.

FUNCTION ZALSM_EXCEL_TO_INTERNAL_TABLE.
*»———————————————————————-
««Локальный интерфейс:
*” IMPORTING
*» VALUE(FILENAME) LIKE RLGRAP-FILENAME
*» VALUE(I_BEGIN_COL) TYPE I
*» VALUE(I_BEGIN_ROW) TYPE I
*» VALUE(I_END_COL) TYPE I
*» VALUE(I_END_ROW) TYPE I
*» REFERENCE(I_SHEET) TYPE I OPTIONAL
*» TABLES
*» INTERN STRUCTURE ZALSMEX_TABLINE
*» EXCEPTIONS
*» INCONSISTENT_PARAMETERS
*» UPLOAD_OLE
*»———————————————————————-

DATA: excel_tab TYPE ty_t_sender.
DATA: ld_separator TYPE c.
DATA: application TYPE ole2_object,
workbook TYPE ole2_object,
range TYPE ole2_object,
worksheet TYPE ole2_object.
DATA: h_cell TYPE ole2_object,
h_cell1 TYPE ole2_object.
DATA:
ld_rc TYPE i.

  • Rückgabewert der Methode «clipboard_export «

  • Makro für Fehlerbehandlung der Methods
    DEFINE m_message.
    case sy-subrc.
    when 0.
    when 1.
    message id sy-msgid type sy-msgty number sy-msgno
    with sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
    when others. raise upload_ole.
    endcase.
    END-OF-DEFINITION.

  • check parameters
    IF i_begin_row > i_end_row. RAISE inconsistent_parameters. ENDIF.
    IF i_begin_col > i_end_col. RAISE inconsistent_parameters. ENDIF.

  • Get TAB-sign for separation of fields
    CLASS cl_abap_char_utilities DEFINITION LOAD.
    ld_separator = cl_abap_char_utilities=>horizontal_tab.

  • open file in Excel
    IF application-header = space OR application-handle = -1.
    CREATE OBJECT application ‘Excel.Application’.
    m_message.
    ENDIF.
    CALL METHOD OF application ‘Workbooks’ = workbook.
    m_message.
    CALL METHOD OF workbook ‘Open’ EXPORTING #1 = filename.
    m_message.

  • set property of application ‘Visible’ = 1.

  • m_message.

IF i_sheet IS NOT INITIAL.
CALL METHOD OF application ‘Sheets’ = worksheet EXPORTING #1 = i_sheet.
CALL METHOD OF worksheet ‘Activate’.

  • CALL METHOD OF worksheet ‘ACTIVESHEET’.
    ELSE.
    GET PROPERTY OF application ‘ACTIVESHEET’ = worksheet.
    ENDIF.

  • GET PROPERTY OF application ‘ACTIVESHEET’ = worksheet.

m_message.

  • mark whole spread sheet
    CALL METHOD OF worksheet ‘Cells’ = h_cell
    EXPORTING #1 = i_begin_row #2 = i_begin_col.
    m_message.
    CALL METHOD OF worksheet ‘Cells’ = h_cell1
    EXPORTING #1 = i_end_row #2 = i_end_col.
    m_message.

    CALL METHOD OF worksheet ‘RANGE’ = range
    EXPORTING #1 = h_cell #2 = h_cell1.
    m_message.
    CALL METHOD OF range ‘SELECT’.
    m_message.

  • copy marked area (whole spread sheet) into Clippboard
    CALL METHOD OF range ‘COPY’.
    m_message.

  • read clipboard into ABAP
    CALL METHOD cl_gui_frontend_services=>clipboard_import
    IMPORTING
    data = excel_tab
    EXCEPTIONS
    cntl_error = 1

  • ERROR_NO_GUI         = 2
    
  • NOT_SUPPORTED_BY_GUI = 3
    OTHERS     = 4.
    

    IF sy-subrc <> 0.
    MESSAGE a037(alsmex).
    ENDIF.

    PERFORM separated_to_intern_convert TABLES excel_tab intern
    USING ld_separator.

  • clear clipboard
    REFRESH excel_tab.
    CALL METHOD cl_gui_frontend_services=>clipboard_export
    IMPORTING
    data = excel_tab
    CHANGING
    rc = ld_rc
    EXCEPTIONS
    cntl_error = 1

  • ERROR_NO_GUI         = 2
    
  • NOT_SUPPORTED_BY_GUI = 3
    OTHERS     = 4.
    
  • quit Excel and free ABAP Object — unfortunately, this does not kill

  • the Excel process
    CALL METHOD OF application ‘QUIT’.
    m_message.

  • Begin of change note 575877

  • to kill the Excel process it’s necessary to free all used objects
    FREE OBJECT h_cell. m_message.
    FREE OBJECT h_cell1. m_message.
    FREE OBJECT range. m_message.
    FREE OBJECT worksheet. m_message.
    FREE OBJECT workbook. m_message.
    FREE OBJECT application. m_message.

  • <<<<< End of change note 575877
    ENDFUNCTION.

Like this post? Please share to your friends:
  • Alphabetical order word cards
  • Alphabetical dictionary word list
  • Alphabet list in word
  • Alot is not a word
  • Alone is a word not meant for you