Partager via


Spécifier une adresse de plage et le nom de la feuille

Cet exemple montre comment spécifier des plages d'adresses à l'aide de coordonnées de plage, ainsi que de plages, de lignes et de colonnes nommées. It also shows how to specify a sheet name and the relationship between a sheet name and a range address.

Les coordonnées de plage sont les quatre coordonnées de type entier utilisées pour sélectionner une plage dont les éléments sont contigus. Les coordonnées de plage vous permettent de spécifier des plages Excel à l'aide d'une indexation directe avec des nombres entiers, comme alternative aux expressions de type « A1 ». Les coordonnées que vous spécifiez sont : la ligne supérieure, la colonne de gauche, la hauteur et la largeur. Il est plus facile d'utiliser des coordonnées de plage quand vous avez du code qui effectue des itérations en boucle à travers un ensemble de cellules, ou quand les coordonnées de plage sont calculées dynamiquement dans le cadre de l'algorithme. Une spécification de plage doit contenir un nom de feuille ; Excel Web Services ne reconnaît pas la « feuille active ». Il existe plusieurs façons de spécifier le nom de la feuille :

  • En tant que partie de l'adresse de la plage, par exemple « Sheet3!B12:D18 », auquel cas l'argument du nom de feuille peut être vide :
  
object[] rangeResult1 = xlservice.GetRangeA1(sessionId, String.Empty, "Sheet2!A12:G18", true, out outStatus);
  Dim rangeResult1() As Object = xlservice.GetRangeA1(sessionId, String.Empty, "Sheet2!A12:G18", True, outStatus)
  • Dans un argument de nom de feuille distinct, auquel cas l'argument d'adresse de plage ne doit pas inclure le nom de feuille :
  xlservice.SetCell(sessionId, "Sheet3", 0, 11, 1000);
  xlservice.SetCell(sessionId, "Sheet3", 0, 11, 1000)
  • In both the sheet name and range address, in which case the name of the sheet must match:
  object[] rangeResult = xlservice.GetCellA1(sessionId, "Sheet3", "Sheet3!G18", true, out outStatus);
  Dim rangeResult() As Object = xlservice.GetCellA1(sessionId, "Sheet3", "Sheet3!G18", True, outStatus)

The only case that does not require a sheet name is a named range, because some named ranges have a workbook scope. For example, you can refer to named ranges without specifying the sheet name argument:

xlServices.SetCellA1(sessionId, String.Empty, "MyNamedRange", 8);
xlServices.SetCellA1(sessionId, String.Empty, "MyNamedRange", 8)

If you specify a sheet name, the ranges you reference must exist on the sheet you specify. Si vous spécifiez une feuille qui n'existe pas, l'appel échoue et vous obtenez une exception SOAP (Simple Object Access Protocol) indiquant que la feuille n'existe pas.

Exemple

Remarque

Cette étape suppose que vous ayez déjà créé une bibliothèque de documents SharePoint qui soit un emplacement approuvé. Pour plus d'informations, voir How to: Trust a Location et How to: Trust Workbook Locations Using Script.

using System;
using System.Text;
using System.Web.Services.Protocols;
using ExcelWebService.myserver02;
namespace ExcelWebService
{
/// <summary>
/// Summary description for Class1.
/// </summary>
    class MyExcelWebService
    {
        [STAThread]
        static void Main(string[] args)
        {
            // Instantiate the Web service 
            // and range coordinate array object.
            ExcelService xlservice = new ExcelService();
            Status[] outStatus;
            RangeCoordinates rangeCoordinates = new RangeCoordinates();
            string sheetName = "MySheet1";

            // TODO: Change the path to the workbook
            // to point to a workbook you have access to.
            // The workbook must be in a trusted location.
            // Using the workbook path this way will allow 
            // you to call the workbook remotely.
            string targetWorkbookPath = 
       "http://myserver02/example/Shared%20Documents/MyWorkbook1.xlsx";

            // Set Credentials for requests
            xlservice.Credentials = 
                System.Net.CredentialCache.DefaultCredentials;

            try
            {
                // Call the open workbook, and point to    
                // the workbook to open.
                string sessionId = 
                    xlservice.OpenWorkbook(targetWorkbookPath, 
                        String.Empty, String.Empty, out outStatus);
                // Prepare object to define range coordinates
                // and call the GetRange method.
                // startCol, startRow, startHeight, and startWidth
                // get their values from user input.
                rangeCoordinates.Column = (int)startCol.Value;
                rangeCoordinates.Row = (int)startRow.Value;
                rangeCoordinates.Height = (int)startHeight.Value;
                rangeCoordinates.Width = (int)startWidth.Value;

                object[] rangeResult1 = xlservice.GetRange(sessionId, 
                    sheetName, rangeCoordinates, false, out outStatus);
                Console.WriteLine("Total rows in range: " + 
                    rangeResult1.Length);
                Console.WriteLine("Sum in last column is: " + 
                    ((object[])rangeResult1[18])[11]);

                // Call the SetCell method, which invokes 
                // the Calculate method.
                // Set first row in last column cell to 1000.
                xlservice.SetCell(sessionId, sheetName, 0, 11, 1000);

                // Call the GetRange method again to see if 
                // the Sum total in the last column changed.
                object[] rangeResult2 = xlservice.GetRange(sessionId, 
                    sheetName, rangeCoordinates, false, out outStatus);    
                Console.WriteLine("Sum in the last column after SetCell 
                    is: " + ((object[])rangeResult2[18])[11]); 

                // Close workbook. This also closes the session.
                xlservice.CloseWorkbook(sessionId);
            }

            catch (SoapException e)
            {
                Console.WriteLine("Exception Message: {0}", e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception Message: {0}", e.Message);
            }
            Console.ReadLine();
        }
    }
}

Imports System
Imports System.Text
Imports System.Web.Services.Protocols
Imports ExcelWebService.myserver02
Namespace ExcelWebService
''' <summary>
''' Summary description for Class1.
''' </summary>
    Friend Class MyExcelWebService
        <STAThread> _
        Shared Sub Main(ByVal args() As String)
            ' Instantiate the Web service 
            ' and range coordinate array object.
            Dim xlservice As New ExcelService()
            Dim outStatus() As Status
            Dim rangeCoordinates As New RangeCoordinates()
            Dim sheetName As String = "MySheet1"

            ' TODO: Change the path to the workbook
            ' to point to a workbook you have access to.
            ' The workbook must be in a trusted location.
            ' Using the workbook path this way will allow 
            ' you to call the workbook remotely.
            Dim targetWorkbookPath As String = "http://myserver02/example/Shared%20Documents/MyWorkbook1.xlsx"

            ' Set Credentials for requests
            xlservice.Credentials = System.Net.CredentialCache.DefaultCredentials

            Try
                ' Call the open workbook, and point to    
                ' the workbook to open.
                Dim sessionId As String = xlservice.OpenWorkbook(targetWorkbookPath, String.Empty, String.Empty, outStatus)
                ' Prepare object to define range coordinates
                ' and call the GetRange method.
                ' startCol, startRow, startHeight, and startWidth
                ' get their values from user input.
                rangeCoordinates.Column = CInt(Fix(startCol.Value))
                rangeCoordinates.Row = CInt(Fix(startRow.Value))
                rangeCoordinates.Height = CInt(Fix(startHeight.Value))
                rangeCoordinates.Width = CInt(Fix(startWidth.Value))

                Dim rangeResult1() As Object = xlservice.GetRange(sessionId, sheetName, rangeCoordinates, False, outStatus)
                Console.WriteLine("Total rows in range: " &amp; rangeResult1.Length)
                Console.WriteLine("Sum in last column is: " &amp; (CType(rangeResult1(18), Object()))(11))

                ' Call the SetCell method, which invokes 
                ' the Calculate method.
                ' Set first row in last column cell to 1000.
                xlservice.SetCell(sessionId, sheetName, 0, 11, 1000)

                ' Call the GetRange method again to see if 
                ' the Sum total in the last column changed.
                Dim rangeResult2() As Object = xlservice.GetRange(sessionId, sheetName, rangeCoordinates, False, outStatus)
                Console.WriteLine("Sum in the last column after SetCell is: " &amp; (CType(rangeResult2(18), Object()))(11))

                ' Close workbook. This also closes the session.
                xlservice.CloseWorkbook(sessionId)

            Catch e As SoapException
                Console.WriteLine("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

Programmation robuste

Make sure you add a Web reference to an Excel Web Services site to which you have access. Change the following:

  • Modifiez l’instruction using ExcelWebService.myserver02; pour qu’elle pointe vers le site de service Web que vous référencez.

  • Modifiez string targetWorkbookPath = "http://myserver02/example/Shared%20Documents/Book1.xlsx"; pour pointer vers un classeur auquel vous avez accès. Le classeur doit se trouver à un emplacement approuvé.

Voir aussi

Tâches

How to: Get Values from Ranges

How to: Set Values of Ranges

Concepts

Accès à l'API SOAP

Autres ressources

Procédure pas à pas : développement d'une application personnalisée à l'aide des services Web Excel