This tutorial shows how to read data from an excel worksheet and display the result on the SAP screen.
We have a duty roster that maps malicious codes to the responsible employee. We want to determine an employee according to the code that has been typed in.


We add a new inputfield, a pushbutton and an outputfield to the SAP screen:

GuiXT

inputfield (20,1) "Read user to code from excel-file" (20,35) _ 
    size="25" name="code"  default="TSC99"  -upperCase

inputfield (20,70) size="15" name="usertocode" _
    -upperCase -noLabel
pushbutton (20,62) "ok" _
    process="read_excel_va03.txt"

In the InputScript "read_excel_va03.txt" we call a .NET (VB/C#) function and pass to it the name of the file and the code as a parameter:

GuiXT

callvb utilities.exceldotnet.TestReadCellsExcel _
    "D:\Excel\duty_rota.xlsx" "&V[code]"
return

We implement the function "TestReadCellsExcel" in our class "exceldotnet" within the class library "utilities.dll". For interacting with MS Excel we make use of the interface that Microsoft provides, therefore we add a reference to the relevant class library to our project and also import the name space into our class:

using guinet;
using Microsoft.Office.Interop.Excel;


public class exceldotnet
{
    public string TestReadCellsExcel(
        string filename,
        string code)
    {
        string returncode = "1";
        Application oXL = null;
        guixt g = new guixt();

        try
        {
            Workbook oWB;
            dynamic oSheet;

            oXL = (Application)
                System.Activator.CreateInstance(
                    System.Type.GetTypeFromProgID(
                        "Excel.Application"));
            oXL.Visible = false;

            oWB = oXL.Workbooks.Open(filename);
            oSheet = oWB.ActiveSheet;

            Range range = oSheet.UsedRange;
            int c = 1;

            foreach (Range r in range.Rows)
            {
                object cellValue =
                    oSheet.Cells(c, 1).Value;

                if (cellValue.ToString() == code)
                {
                    object userValue =
                        oSheet.Cells(c, 2).Value;
                    g.SetVariable(
                        "usertocode",
                        userValue.ToString());
                    returncode = "0";
                    break;
                }
                c++;
            }
        }
        catch
        {
            oXL.ActiveWorkbook.Close(false);
            oXL.Quit();
            return "Exception";
        }

        oXL.ActiveWorkbook.Close(false);
        oXL.Quit();

        return returncode;
    }
}

In line 29 we put the name of the responsible employee into a GuiXT variable directly, which means that this data is displayed on the SAP screen immediately.

NB: Although MS Excel is called via .NET (VB/C#) interface and runs invisibly, it still has to be installed on the client PC.


The result:

 

 

Download Excel scripts (ZIP)