C# 调用 SAP RFC 方法

来源:互联网 发布:罗技m280 m330 知乎 编辑:程序博客网 时间:2024/04/29 12:51

添加SAP安装程序的四个dll文件引用:

Interop.SAPBAPIControlLib.dll
Interop.SAPFunctionsOCX.dll
Interop.SAPLogonCtrl.dll
Interop.SAPTableFactoryCtrl.dll

 

 

调用方法体:

private void GetMateriel()
    {
        string number = this.txtNumber.Text.Trim();
        string desc = this.txtDesc.Text.Trim();

        Config config = new Config();
        SAPLogonCtrl.SAPLogonControlClass login = new SAPLogonCtrl.SAPLogonControlClass();

        login.ApplicationServer = config.Server;
        login.Client = config.Client;
        login.Language = config.Language;
        login.User = config.User;
        login.Password = config.Password;
        login.SystemNumber = config.Number;

        SAPLogonCtrl.Connection conn = (SAPLogonCtrl.Connection)login.NewConnection();
        DataSet ds = new DataSet();
        DataTable table = new DataTable();
        table.Columns.Add("Number", typeof(string));
        table.Columns.Add("Desc1", typeof(string));
        table.Columns.Add("Desc2", typeof(string));
        table.Columns.Add("Desc3", typeof(string));
        table.Columns.Add("Uint", typeof(string));

        if (conn.Logon(0, true))
        {
            SAPFunctionsOCX.SAPFunctionsClass func = new SAPFunctionsOCX.SAPFunctionsClass();
            func.Connection = conn;

            SAPFunctionsOCX.IFunction ifunc = (SAPFunctionsOCX.IFunction)func.Add("Z_MATERIAL_APPLICATION"); //(Z_MATERIAL_APPLICATION) SAP RFC 名称

            SAPFunctionsOCX.IParameter gclient = (SAPFunctionsOCX.IParameter)ifunc.get_Exports("I_WERKS"); //(I_WERKS)输入参数
            gclient.Value = Factory; //(Factory)对参数赋值

            SAPFunctionsOCX.IParameter matnr = (SAPFunctionsOCX.IParameter)ifunc.get_Exports("I_MATNR");
            matnr.Value = number;

            SAPFunctionsOCX.IParameter maktx = (SAPFunctionsOCX.IParameter)ifunc.get_Exports("I_MAKTX");
            maktx.Value = desc;

            ifunc.Call();
            SAPTableFactoryCtrl.Tables tables = (SAPTableFactoryCtrl.Tables)ifunc.Tables;
            SAPTableFactoryCtrl.Table ENQ = (SAPTableFactoryCtrl.Table)tables.get_Item("PO_TAB"); (PO_TAB)输出表名

            for (int i = 1; i <= ENQ.RowCount; i++)
            {
                DataRow dr = table.NewRow();
                dr[0] = ENQ.get_Cell(i, "MATNR");
                dr[1] = ENQ.get_Cell(i, "MAKTX");
                dr[2] = ENQ.get_Cell(i, "MAKTX2");
                dr[3] = ENQ.get_Cell(i, "MAKTX3");
                dr[4] = ENQ.get_Cell(i, "MEINS");
                table.Rows.Add(dr);
            }

            ds.Tables.Add(table);
        }
        conn.Logoff();

        this.Repeater1.DataSource = ds.Tables[0];
        this.DataBind();
        this.lblCount.Text = "共找到" + ds.Tables[0].Rows.Count.ToString() + "條記錄";
        ScriptManager.RegisterStartupScript(btnSAP, this.GetType(), "", "$(document).ready( function (){ jQuery.page('page',10);} )", true);
    }