GRC
HR
SCM
CRM
BI
Expand +


Article

 

Steps to Output a Microsoft Word Document from an SAP System

by Said Belahbib, SAP HCM and FI/CO Technical Quality Manager

December 4, 2017

Many companies start producing and generating their documentation in Microsoft Word, and this method works fine for a small number of documents. However, over time as business needs grow, this method becomes increasingly difficult to manage. One solution is to migrate documents from Word to an XML-based file format that is easy to parse with an SAP system. Here are four steps to output an employee agreement contract in Word format so that end users can modify the document if needed, store it, and link it to the employee. This tailored solution is based on standard SAP functionality. With it you can optimize document-based processes for any industry and companies of any size. This solution can be used for any SAP system and Microsoft interface.


Companies often need to interface Microsoft Word with their SAP systems. For example, you may need to output an employee document in a Word format that all the company’s employees know how to handle so that they can modify the content if needed. Using the example of a contract with an employee, I show how to store your file within your SAP system using an SAP Web Repository and a MIME Repository, how to handle the file content and modify it according to business requirements, and how to output a web file from a Word document.

In this next section, I present the steps to achieve the display of an employee agreement contract from an SAP system using master data and standard functionality in Word format. The method can be extended to any other process within SAP ERP. Figure 1 highlights the most important steps.


Figure 1
The steps to display a Word document with embedded SAP master data

Step 1. Prepare the File Template

In this step, use a Word file with the extension .docx, Microsoft started using .docx files in Word beginning with Word 2007. Earlier versions of Word use the .doc file extension. You prepare the document so that you can feed it with the right master data in Word. To do so, proceed as follows. Figure 2 shows the contract employee sample agreement with the naming convention to adopt to fill the dynamic fields with master data coming from the SAP system. The formatting fields (such as EmployeeName and SystemDate) help you to capture attributes that you replace within the text.


Figure 2
Example of a Word contract document

The dynamic field must have a characteristic (such as EmployeeName in one word rather Employee Name) to differentiate it from the rest of the text to facilitate the replacement with employee master data. This approach facilitates the process of finding and replacing text within a Word document. For example, you can name your dynamic field $Employee Name$ instead of EmployeeName.

When you open Word, an option allows you to save documents in a Word Open XML format. Click File and select the Save As… option (Figure 3).


Figure 3
Convert your Word document to an XML file

Save your file document contract_employee_agreement_sample.docx into an XML format as shown in Figure 4.


Figure 4
Save your document as a Word XML document (.xml)

Figure 4 shows you the extension .xml you should adopt to ease the parsing of the document and the replacement of the dynamic fields with the right data. The reason to do so is that it is hard to parse documents with the extension .docx as it requires a lot of effort and ABAP development to read the file.

Step 2. Manage the Document Within the SAP System

In this step, you to store your template XML document in SAP ERP, as shown in Figure 4. Once you create your file named Contract_employee_agreement_sample.xml, you can upload it into the SAP system using two different options:

Option 1: Store the XML template in the SAP Web Repository via transaction code SMW0. This method is useful when you are dealing with different contracts for different company codes. In this article, I focus only on the simple option for storing an XML file template in the SAP system. Run transaction code SMW0. Click the HTML templates for WebRFC applications radio button as shown in Figure 5. Click the find  icon .


Figure 5
Option to store the XML file in the SAP system

Once you click the find icon you see the prompt shown in Figure 6.


Figure 6
Screen to search for a specific object

Click the execute icon . Leave all the fields blank to see the prompt in Figure 7.


Figure 7
Results of the search

Figure 7 shows you all existing objects stored in your system. The create icon  allows you to create a new XML template. Click it to upload your XML template in the SAP system. The system then displays a pop-up screen (Figure 8).


Figure 8
Create a contract template and store it in an SAP system

In Figure 9, you provide the Obj. name, which is the SAP www.gateway object name. In my example, you enter the value ZHRexpertonline and the short text Employee Agreement Contract in the Description field. Click the import icon  to upload the XML file you saved as Contract_employee_agreement_sample in Figure 4.


Figure 9
File selection to import the contract template into the SAP system

Click the Open button to import your file into the SAP Web Repository. You are prompted to the next screen to select your package in which you save your object name, as shown in Figure 10.


Figure 10
Save your file as a local object

In my example, save the object locally by clicking the Local Object button instead of the save icon .  Once you save your file, you see it is added in the SAP Web Repository (Figure 11). In this step you save locally unless you select a package to transport your objects to the quality or production systems.


Figure 11
The contract file template is saved in the SAP Web Repository

Option 2: Store the XML template in the SAP MIME Repository. Navigate to the ABAP Workbench via transaction code SE80. Click the MIME Repository option and first create your own folder where you store your template as shown in Figure 12. In my example I create the ContractMgt folder.


Figure 12
Create your folder to store your template file

Right-click the PUBLIC folder, and in the next screen (Figure 13) create your folder. Fill the Description field and save the screen by clicking the save icon .


Figure 13
Name your folder to store the contract template

Once you create the folder, you upload your file as shown in Figure 14. Right-click the ContractMgt folder to upload your XML template, by selecting Import MIME Objects.


Figure 14
Import your contract template file

In this step, you display the browse dialog that appears. Navigate to the directory where you saved the contract template and select the file Contract_employee_agreement_sample.xml.

Your template file is saved in the MIME repository in the ContractMgt folder. As shown in Figure 15, follow menu path SAP > PUBLIC > ContractMgt > Contract_employee_agreement_sample.xml to access your file. Using your ABAP code, you parse the file and replace the dynamic fields with employee master data.


Figure 15
Select your contract template to store in the MIME repository

Step 3. Technical Enhancement

In this step you have to identify the requirement for which the enhancement needs to be created. Essentially, a data mapping specification analyzes field by field how to move data from the SAP system to Word.

Data mapping: To achieve this goal, a data mapping specification contains the following elements:

  • A list of attributes for the original source of data (attributes to replace in the XML file)
  • A corresponding (or mapped) list of attributes for the target data repository (attributes from SAP infotypes, such as infotypes 0001, 0002, and 0006)

Translation rules define any data manipulation that needs to happen as information moves between the SAP system and the Word document, such as setting default values, combining fields, or mapping values.

Table 1 shows the infotype used in my example to replace fields in a Word document with employee master data. You use function module RH_READ_INFTY_1000 to get the employee job title and you get the hiring date by using function module RP_GET_HIRE_DATE.

Field description

Word attributes

Data manipulation

Mapped data (from infotypes)

System date

SytemDate

Default value

sy-datum

Employee full name

EmployeeFullName

P0002- CNAME

Employee private address

EmployeeAddress

Concatenate fields

P0006-STRAS, P0006-ORT01, P0006-PSTLZ, P0006-LAND1

Company name

CompanyName

Default value

Default value: Company Name

Employee job title

JobTitle

Combination fields

HRP1000-STEXT,  HRP1000-otype = 'C' (C for Job),  HRP1000-objid = P0001-STELL

Hiring date

HiringDate

P0000-begda

Table 1
Data mapping grid

Step 4. Process and Read the Template File

In this step, you deliver the source code snippets that help to read the template XML file stored in the SAP Web Repository (Figure 11) and in the MIME Repository (Figure 15).

Case 1: Read the file from MIME Repository. In Figure 16, you read your XML file and you replace all the dynamic fields as entered in the contract template (Figure 2). In this report, you have declared lt_msword, which is an internal table that helps you to display the contract agreement as a Word document.

*   DATA declaraction

DATA:

      lc_mr_api     TYPE REF TO if_mr_api,

      l_text_x        TYPE xstring,

      lc_conv_in    TYPE REF TO cl_abap_conv_in_ce,

      l_bom           TYPE x LENGTH 3,

      l_string         TYPE string,

      lt_string        TYPE string_table.

      lt_msword      TYPE string_table.

 

    lc_mr_api = cl_mime_repository_api=>get_api( ).

 

    lc_mr_api->get(

      EXPORTING

        i_url = '/SAP/PUBLIC/Contract/ Contract_employee_agreement_sample.xml' " the mime path (figure 15)

      IMPORTING

        e_content                 = l_text_x

      EXCEPTIONS

        parameter_missing  = 1

        error_occured          = 2

        not_found                = 3

        permission_failure   = 4

        OTHERS                 = 5

    ).

 

*   Trick to Remove the Byte Order Mark UTF8, when exists (more information click here)

    l_bom = l_text_x.

    IF l_bom EQ cl_abap_char_utilities=>byte_order_mark_utf8.

      l_text_x = l_text_x+3.

    ENDIF.

 

    lc_conv_in  = cl_abap_conv_in_ce=>create( encoding = 'UTF-8' ).

 

    lc_conv_in->convert(

      EXPORTING

        input   = l_text_x

      IMPORTING

        data    = l_string

    ).

 

    SPLIT l_string AT cl_abap_char_utilities=>cr_lf INTO TABLE lt_string.

*     Loop on lt_string table to replace dynamic fields with employee master data from Infotype

      loop at lt_string into l_string.

*     Replace dynamic field with SAP Master data

      REPLACE 'EmployeeName' WITH P0002- CNAME INTO l_xml_line. “ do it for all dynamic fields

      append l_xml_line into lt_msword. “ lt_msword is the word document we display with SAP master data

      ENDLOOP.

 

   

Figure 16
Sample source code to read the XML file template from the MIME Repository

Figure 16 is sample ABAP source code that you need to adapt to your business requirements.

Case 2: Read the file from SAP Web Repository. In Figure 17, you read your XML file and you replace all the dynamic fields you have populated in the contract template (Figure 2). In this report, I have declared l_xml_line. which is an internal table that helps to display the contract agreement as a Word document.

 

*     Data Declaration

    DATA: l_xml_line          TYPE xstring,

                 l_object_id          TYPE w3objid,

                 l_object_key       TYPE wwwdatatab,

                 t_mime_raw       TYPE STANDARD TABLE OF w3mime,

                 ls_mime_raw      TYPE w3mime.

 

*     Import the xml file template, stored in web repository with

*     transaction SMW0

    l_object_key-objid = 'ZHREXPERTONLINE'.

    l_object_key-relid = 'HT'.

 

*   Import Web Object (Figure 11 in our example)

    CALL FUNCTION 'WWWDATA_IMPORT'

      EXPORTING

        key = l_object_key

      TABLES

        mime = t_mime_raw

      EXCEPTIONS

        wrong_object_type = 1

        import_error = 2

        OTHERS = 3.

*    ... build a long xstring

    IF sy-subrc EQ 0.

      LOOP AT t_mime_raw INTO ls_mime_raw.

        CONCATENATE l_xml_line ls_mime_raw-line INTO l_xml_line IN BYTE MODE.

*     Relace dynamic field with SAP Master data

      REPLACE 'EmployeeName' WITH P0002- CNAME INTO l_xml_line. “ do it for all dynamic fields

      “ In this case is the l_xml_line we display as word document.

      ENDLOOP.

    ENDIF.

 

Figure 17
Source code to read the XML file template from SAP Web Repository

The final step is to convert the internal table in the Word document (contract document).

Figures 16 and 17 show the code for reading the file and replacing all the dynamic fields with SAP ERP HCM master data. In this step, you can download your internal table t_mime_raw into the Word file document and open it with the Word document.

Figure 18 shows that you can open the Word document file with the CALL_BROWSER function module. You see also that I gave the extension .docx to the generated contract file.


Figure 18
Code snippet to open the Word document

Step 5. Use a Dynamic Action

You use a dynamic action to create or modify a new record in infotype 0016. A dynamic action allows you to define some specific behaviors while executing an action depending, for example, on the values of the last infotype filled and so on. Dynamic actions are basically controls that can be initiated after certain actions during employee maintenance or personnel actions. This is mostly configurable using standard utilities provided by SAP unless there is a special requirement for which you need to develop a function module with specific program logic that can be called during any specific infotype maintenance to create, update, or take any other specific actions on other infotypes.

Most of the requirements can be configured using table T588Z. For more information, click this SAP Help link that explains how to configure a dynamic action by illustrating different scenarios. For my example, while creating or modifying infotype 0016 (Contract Elements), you display the employee agreement contract.

[https://help.sap.com/doc/saphelp_46c/4.6.C/en-US/57/5184ab7b35d111950d0060b03c6b76/frameset.htm]

Until now I have used XML files, but the same process can be undertaken with HTML files if you want to store document files as web documents in SAP Enterprise Portal. The only difference is that instead of saving it in the XML template, you save the employee contract document in the web page.

Figure 4 shows you how to save your file. Similarly Figure 19 shows you how to generate an .html file.

Click File > Save As and choose the location where you want to save your document.


Figure 19
Save your document web page

In this part, I provide source code for handling XML and HTML templates and replacing variables with SAP ERP HCM master data. Figure 20 shows the ABAP source code to read the HTML file you saved in the SAP Web repository via transaction code SMW0.

REPORT  ZREAD_FROM_SMW0

  • ************** Declare the SWWW Type-Pool ***********************

TYPE-POOLS: swww.

  • **************** Data Declarations *********************************

DATA: lt_merge_table        TYPE  swww_t_merge_table.

DATA: lt_html_table            TYPE  swww_t_html_table.

DATA: ls_merge_table       LIKE LINE OF lt_merge_table.

DATA: ls_html_table           LIKE LINE OF lt_html_table.

DATA:  L_APP_TYPE         TYPE STRING,

             L_FILENAME         TYPE STRING,

             L_XSTRING           TYPE XSTRING,    "needed for HTTP response

             L_XLEN                                  TYPE I.

DATA: lv_string                                   TYPE string.

  • ************************* Selection Screen ****************************

PARAMETERS: p_temp     TYPE swww_t_template_name DEFAULT 'ZHREXPERTONLINE2'. “ file you store in SMW0

PARAMETERS: p_user      TYPE syuname DEFAULT sy-uname.  “ this is just an example 

PARAMETERS: p_date      TYPE sydatum DEFAULT sy-datum.    “ educational example

START-OF-SELECTION.

  REFRESH lt_html_table.

  • ********** Remplace EmployeeName with its value ********

  CLEAR ls_merge_table.

  ls_merge_table-name    = 'EmployeeName'.

  ls_merge_table-command = 'R'.

  lv_string              = p_user.

  APPEND LV_string to ls_merge_table-html[].

  APPEND ls_merge_table TO lt_merge_table.

*

  • ***********Replace EmployeeDate with its value *************

  CLEAR ls_merge_table.

  ls_merge_table-name    = 'SystemDate'.

  ls_merge_table-command = 'R'.

  lv_string              = p_date.

  APPEND LV_string to ls_merge_table-html[].

  APPEND ls_merge_table TO lt_merge_table.

*

  • ************** Call the HTML MERGE function **********************

  CALL FUNCTION 'WWW_HTML_MERGER'

    EXPORTING

      template    = p_temp

    IMPORTING

      html_table  = lt_html_table[]

    CHANGING

      merge_table = lt_merge_table[].

END-OF-SELECTION.

DATA: BEGIN OF string_tab_row,

            col TYPE STRING,

          END OF string_tab_row.

  DATA string_tab LIKE TABLE OF string_tab_row.

  LOOP AT lt_html_table INTO ls_html_table.

    WRITE / ls_html_table-line.

    string_tab_row-col = ls_html_table-line.

    append string_tab_row to string_tab.

  ENDLOOP.

  CALL FUNCTION 'GUI_DOWNLOAD'

    EXPORTING

      FILENAME              = '/Users/HRexpert/Downloads/mydownl.htm' " put here your own path

      WRITE_FIELD_SEPARATOR = ''

    TABLES

      DATA_TAB              = string_tab.

 CALL FUNCTION 'CALL_BROWSER'

  EXPORTING

    URL        = '/Users/HRexpert/Downloads/mydownl.htm'

    .

Figure 20 Source code for handling XML and HTML templates and replacing variables with SAP ERP HCM master data

Figure 21 shows the Word document (Contract_employee_agreement_sample.docx) with the correspondence between the ERP system and the Word agreement template. 


Figure 21
Sample template agreement document

Figure 22 displays the file content in the SAP screen without any change (left side), and the corresponding dynamic fields in the Word document (right side).


Figure 22
Output screen while reading the HTML file from the SAP Web Repository

Figure 23 shows you how to fill the internal table lt_merge_table and pass it to the function module WW_HTML_MERGER.


Figure 23
ABAP source code to call the file from the SAP Web Repository and modify variables according to your requirements

In this last step, you call your function module by setting the command to R (R stands for replace), as shown in Figure 23 (ls_merge_table-command = R).

An email has been sent to:





 

Said Belahbib

Said Belahbib has a Ph.D. in nuclear physics and an MBA (European Management for the Global Market). He works at a university (unil) in Lausanne.

You may contact the author at sbelahbib@gmail.com.



COMMENTS

Please log in to post a comment.

No comments have been submitted on this article. Be the first to comment!


SAPinsider
FAQ