次の方法で共有


手順 3 : Web サービスにアクセスする

最終更新日: 2010年1月21日

適用対象: SharePoint Server 2010

Excel Web Services への参照をプロジェクトに追加した後の次の手順は、Web サービスのプロキシ クラスのインスタンスを作成することです。そのようにすると、Web サービスのメソッドには、プロキシ クラスのメソッドを呼び出すことによってアクセスできます。アプリケーションがこれらのメソッドを呼び出すと、Visual Studio によって生成されたプロキシ クラスのコードが、アプリケーションと Web サービスとの間の通信を処理します。

最初に、Web サービスのプロキシ クラス ExcelWebService のインスタンスを作成します。次に、プロキシ クラスを使用して Web サービスのいくつかのメソッドとプロパティを呼び出します。

使用するのは、ブックを開く呼び出し、セッション ID を取得する呼び出し、既定の資格情報を渡す呼び出し、範囲の座標のオブジェクトを定義する呼び出し、範囲の座標のオブジェクトを使用する範囲を取得する呼び出し、ブックを閉じる呼び出し、および SOAP 例外をキャッチする呼び出しです。

Web サービスにアクセスする

ディレクティブを追加するには

  1. 前に Web 参照を追加したときに、<プロジェクト名>.<Web 参照名> という名前の名前空間に、ExcelService というオブジェクトが作成されました。この例では、オブジェクトの名前は SampleApplication.ExcelWebService になります。このウォークスルーでは、SOAP 例外をキャッチする方法も示します。そのためには、System.Web.Services.Protocols オブジェクトを使用します。System.Web.Services.Protocols 名前空間は、プロトコルを定義するクラスから構成されます。このプロトコルは、XML Web サービス クライアントと、ASP.NET を使用して作成された XML Web サービスとの間の通信中に、回線を経由するデータ送信に使用されます。
    これらのオブジェクトを使いやすくするため、最初に、名前空間をディレクティブとして Class1.cs ファイルに追加する必要があります。こうすれば、それらのディレクティブを使用する場合に、名前空間内の型を完全に修飾する必要がありません。

  2. これらのディレクティブを追加するには、Class1.cs ファイルのコードの最初に、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. SOAP 例外をキャッチして例外メッセージを出力する catch ブロックを追加します。

    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 にアクセスする

その他の技術情報

[方法] スクリプトを使用してブックの場所を信頼する