步骤 3:访问 Web 服务

上次修改时间: 2010年1月21日

适用范围: SharePoint Server 2010

当您向项目添加 Excel Web Services 的引用后,下一步就是创建 Web 服务代理类的实例。然后便可以通过调用代理类中的方法来访问 Web 服务的方法。当应用程序调用这些方法时,由 Visual Studio 生成的代理类代码将处理应用程序与 Web 服务之间的通信。

首先,创建 Web 服务代理类 ExcelWebService 的一个实例。然后用该代理类调用 Web 服务的几个方法和属性。

您可以通过调用来打开工作簿,获取会话 ID,传递默认凭据,定义区域坐标对象,获取使用区域坐标对象的区域,关闭工作簿,并捕获 SOAP 异常。

访问 Web 服务

添加指令

  1. 之前在添加 Web 引用时,在 <yourProject>.<webReferenceName> 命名空间中创建了名为 ExcelService 的对象。在本示例中,该对象被命名为 SampleApplication.ExcelWebService。本演练中还演示了如何捕获 SOAP 异常。为此,您需要使用 System.Web.Services.Protocols 对象。System.Web.Services.Protocols 命名空间由定义协议的类组成,在 XML Web Services 客户端与通过 ASP.NET 创建的 XML Web Services 之间的通讯过程中,这些协议用于在线路间传输数据。
    为了便于使用这些对象,您必须首先将命名空间作为指令添加到 Class1.cs 文件。这样,如果使用这些指令,您就无需完全限定命名空间中的类型。

  2. 若要添加这些指令,请将以下代码添加到 Class1.cs 文件代码的开头,位于 using System 之后:

    using SampleApplication.ExcelWebService;
    using System.Web.Services.Protocols;
    
    Imports SampleApplication.ExcelWebService
    Imports System.Web.Services.Protocols
    

调用 Web 服务

  1. 通过在 static void Main(string[] args) 中左方括号的后面添加以下代码,对 Web 服务代理对象进行实例化和初始化:

    ExcelService es = new ExcelService();
    
    Dim es As New ExcelService()
    
  2. 添加以下代码以创建状态数组和区域坐标对象:

    Status[] outStatus;
    RangeCoordinates rangeCoordinates = new RangeCoordinates();
    
    Dim outStatus() As Status
    Dim rangeCoordinates As New RangeCoordinates()
    
  3. 添加代码以指向要访问的工作表。在本示例中,工作表名为"Sheet1"。将以下内容添加到代码中:

    string sheetName = "Sheet1";
    
    Dim sheetName As String = "Sheet1"
    

    备注

    请确保要打开的工作簿中包含"Sheet1"工作表(需包含值)。也可以将代码中的"Sheet1"更改为您的工作表的名称。

  4. 添加以下代码以指向要打开的工作簿:

    string targetWorkbookPath = "http://myserver02/example/Shared%20Documents/Book1.xlsx";
    
    Dim targetWorkbookPath As String = "http://myserver02/example/Shared%20Documents/Book1.xlsx"
    
    重要注释重要说明

    更改工作簿路径以符合此演练中所使用的工作簿的位置。确保工作簿存在并且保存在可靠的位置。通过使用 HTTP URL 指向工作簿的位置,您可以进行远程访问。

    备注

    在 Microsoft SharePoint Server 2010 中,可以通过右键单击工作簿并选择"复制快捷方式"来获得工作簿的路径。此外,也可以选择"属性"并从中复制工作簿的路径。

  5. 添加以下代码以设置请求的凭据。

    备注

    即使您打算使用默认凭据,也必须明确地设置凭据。

    es.Credentials = System.Net.CredentialCache.DefaultCredentials;
    
    es.Credentials = System.Net.CredentialCache.DefaultCredentials
    
  6. 添加以下代码以打开工作簿,并指向工作簿所在的受信任位置。将代码放到 try 块中:

    try
    {
    string sessionId = es.OpenWorkbook(targetWorkbookPath, "en-US", 
        "en-US", out outStatus);
    
    Try
    Dim sessionId As String = es.OpenWorkbook(targetWorkbookPath, "en-US", "en-US", outStatus)
    
  7. 添加以下代码以准备用来定义区域坐标的对象,并调用 GetRange 方法。代码还将打印区域中的总行数和特定区域中的值。

    rangeCoordinates.Column = 3;
    rangeCoordinates.Row = 9;
    rangeCoordinates.Height = 18;
    rangeCoordinates.Width = 12;
    
    object[] rangeResult1 = es.GetRange(sessionId, sheetName,
        rangeCoordinates, false, out outStatus);
    Console.WriteLine("Total rows in range: " + rangeResult1.Length);
    Console.WriteLine("Value in range is: " + ((object[])rangeResult1[5])[2]);
    
    rangeCoordinates.Column = 3
    rangeCoordinates.Row = 9
    rangeCoordinates.Height = 18
    rangeCoordinates.Width = 12
    
    Dim rangeResult1() As Object = es.GetRange(sessionId, sheetName, rangeCoordinates, False, outStatus)
    Console.WriteLine("Total rows in range: " & rangeResult1.Length)
    Console.WriteLine("Value in range is: " & (CType(rangeResult1(5), Object()))(2))
    
  8. 添加代码以关闭工作簿并关闭当前会话。另外在 try 块的结尾添加右方括号。

    重要注释重要说明

    使用完会话后,最好关闭工作簿。这样将关闭会话并释放资源。

    es.CloseWorkbook(sessionId);
    }
    
    es.CloseWorkbook(sessionId)
    
  9. 添加 catch 块以捕获 SOAP 异常并打印异常消息:

    catch (SoapException e)
    {
        Console.WriteLine("SOAP Exception Message: {0}", e.Message);
    }
    
    Catch e As SoapException
        Console.WriteLine("SOAP Exception Message: {0}", e.Message)
    End Try
    

完整代码

以下代码示例是前面步骤中描述的 Class1.cs 示例文件中的完整代码。

重要注释重要说明

根据需要更改工作簿路径、工作表名称等。

using System;
using SampleApplication.ExcelWebService;
using System.Web.Services.Protocols;

namespace SampleApplication
{
    class Class1
    {
        [STAThread]
        static void Main(string[] args)
        {            
            // Instantiate the Web service and create a status array object and range coordinate object
            ExcelService es = new ExcelService();
            Status[] outStatus;
            RangeCoordinates rangeCoordinates = new RangeCoordinates();
            
string sheetName = "Sheet1";
            // Using workbookPath this way will allow 
            // you to call the workbook remotely.
            // TODO: change the workbook path to 
            // point to workbook in a trusted location
            // that you have access to 
            string targetWorkbookPath = "http://myserver02/example/Shared%20Documents/Book1.xlsx";
//you can also use .xlsb files, for example, //"http://myserver02/example/Shared%20Documents/Book1.xlsb";

            // Set credentials for requests
            es.Credentials = System.Net.CredentialCache.DefaultCredentials;
            //Console.WriteLine("Cred: {0}", es.Credentials);
            try
            {
                // Call open workbook, and point to the trusted   
                // location of the workbook to open.
                string sessionId = es.OpenWorkbook(targetWorkbookPath, "en-US", "en-US", out outStatus);
                // Console.WriteLine("sessionID : {0}", sessionId);

                // Prepare object to define range coordinates
                // and the GetRange method.
                rangeCoordinates.Column = 3;
                rangeCoordinates.Row = 9;
                rangeCoordinates.Height = 18;
                rangeCoordinates.Width = 12;

                object[] rangeResult1 = es.GetRange(sessionId, sheetName, rangeCoordinates, false, out outStatus);
                Console.WriteLine("Total Rows in Range: " + rangeResult1.Length);
                Console.WriteLine("Value in range is: " + ((object[])rangeResult1[5])[3]); 
        
                // Close workbook. This also closes session.
                es.CloseWorkbook(sessionId);
            }
            catch (SoapException e)
            {
                Console.WriteLine("SOAP Exception Message: {0}", e.Message);
            }
            // catch (Exception e)
//            {
//                Console.WriteLine("Exception Message: {0}", e.Message);
//            }
//            Console.ReadLine();
        }
    }
}
     
Imports System
Imports SampleApplication.ExcelWebService
Imports System.Web.Services.Protocols

Namespace SampleApplication
    Friend Class Class1
        <STAThread> _
        Shared Sub Main(ByVal args() As String)
            ' Instantiate the Web service and create a status array object and range coordinate object
            Dim es As New ExcelService()
            Dim outStatus() As Status
            Dim rangeCoordinates As New RangeCoordinates()

Dim sheetName As String = "Sheet1"
            ' Using workbookPath this way will allow 
            ' you to call the workbook remotely.
            ' TODO: change the workbook path to 
            ' point to workbook in a trusted location
            ' that you have access to 
            Dim targetWorkbookPath As String = "http://myserver02/example/Shared%20Documents/Book1.xlsx"
'you can also use .xlsb files, for example, //"http://myserver02/example/Shared%20Documents/Book1.xlsb";

            ' Set credentials for requests
            es.Credentials = System.Net.CredentialCache.DefaultCredentials
            'Console.WriteLine("Cred: {0}", es.Credentials);
            Try
                ' Call open workbook, and point to the trusted   
                ' location of the workbook to open.
                Dim sessionId As String = es.OpenWorkbook(targetWorkbookPath, "en-US", "en-US", outStatus)
                ' Console.WriteLine("sessionID : {0}", sessionId)

                ' Prepare object to define range coordinates
                ' and the GetRange method.
                rangeCoordinates.Column = 3
                rangeCoordinates.Row = 9
                rangeCoordinates.Height = 18
                rangeCoordinates.Width = 12

                Dim rangeResult1() As Object = es.GetRange(sessionId, sheetName, rangeCoordinates, False, outStatus)
                Console.WriteLine("Total Rows in Range: " & rangeResult1.Length)
                Console.WriteLine("Value in range is: " & (CType(rangeResult1(5), Object()))(3))

                ' Close workbook. This also closes session.
                es.CloseWorkbook(sessionId)
            Catch e As SoapException
                Console.WriteLine("SOAP Exception Message: {0}", e.Message)
            ' Catch e As Exception
            '    Console.WriteLine("Exception Message: {0}", e.Message)
            End Try
            'Console.ReadLine()
        End Sub
    End Class
End Namespace

请参阅

任务

步骤 1:创建 Web 服务客户端项目

步骤 2:添加 Web 引用

步骤 4:生成和测试应用程序

演练:使用 Excel Web Services 开发自定义应用程序

概念

访问 SOAP API

其他资源

How to: Trust Workbook Locations Using Script