Compartir a través de


Procedimiento para especificar una dirección de rango y nombre de hoja de cálculo

Última modificación: miércoles, 24 de marzo de 2010

Hace referencia a: SharePoint Server 2010

En este ejemplo se muestra cómo especificar direcciones de rango mediante coordenadas rango, denominadas rangos, filas y columnas. También se muestra cómo especificar el nombre de una hoja y la relación entre un nombre de hoja y una dirección de rango.

Las coordenadas de rango son las cuatro coordenadas de enteros usadas para seleccionar un rango contiguo. Las coordenadas de rango permiten especificar rangos de Excel mediante la indización directa de enteros como alternativa a las expresiones "A1". Las coordenadas que puede especificar son la fila superior, la columna izquierda, la altura y la anchura. Es más fácil usar las coordenadas de rango si tiene código que interactúe a través de un conjunto de celdas en un bucle o si las coordenadas de rango se calculan de forma dinámica como parte del algoritmo.

Una especificación de rango debe contener un nombre de hoja; Servicios web de Excel no reconoce la "hoja actual". Hay varias formas para especificar el nombre de la hoja:

  • Como parte de la dirección de rango (por ejemplo, "Sheet3!B12:D18", en cuyo caso el nombre de argumento de hoja puede ser vacío:

    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)
    
  • En un argumento de nombre de hoja independiente, en cuyo caso el argumento de direcciones de rango no tiene que incluir el nombre de la hoja:

    xlservice.SetCell(sessionId, "Sheet3", 0, 11, 1000);
    
    xlservice.SetCell(sessionId, "Sheet3", 0, 11, 1000)
    
  • En ambos, el nombre de hoja y la dirección de rango, en cuyo caso el nombre de la hoja debe coincidir con:

    object[] rangeResult = xlservice.GetCellA1(sessionId, "Sheet3", "Sheet3!G18", true, out outStatus);
    
    Dim rangeResult() As Object = xlservice.GetCellA1(sessionId, "Sheet3", "Sheet3!G18", True, outStatus)
    

El único caso que no requiere un nombre de hoja es un rango con nombre, porque algunos rangos con nombre tienen un ámbito de libro. Por ejemplo, puede hacer referencia a rangos con nombre sin especificar el argumento de nombre de hoja:

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

Si especifica un nombre de hoja, los rangos a los que haga referencia deben existir en la hoja que se especifica. Si especifica una hoja que no existe, la llamada producirá un error y obtendrá una excepción de Protocolo simple de acceso a objetos (SOAP), que indica que la hoja no existe.

Ejemplo

Nota

Se supone que ya ha creado una biblioteca de documentos de SharePoint y que la ha convertido en una ubicación de confianza. Para obtener más información, consulte Procedimiento para confiar en una ubicación y Procedimiento para confiar en ubicaciones de libro mediante secuencia de comandos.

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: " & rangeResult1.Length)
                Console.WriteLine("Sum in last column is: " & (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: " & (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

Programación sólida

Asegúrese de que se agrega una referencia web a un sitio de Servicios web de Excel al que tenga acceso. Cambie lo siguiente:

  • Cambie la instrucción using ExcelWebService.myserver02; que apunte al sitio de servicios web al que se hace referencia.

  • Cambie string targetWorkbookPath = "http://myserver02/example/Shared%20Documents/Book1.xlsx"; para que señale a un libro al que tenga acceso. El libro debe estar en una ubicación de confianza.

Vea también

Tareas

Procedimiento para obtener valores de rangos

Procedimiento para establecer valores de rangos

Tutorial: Desarrollar una aplicación personalizada mediante Excel Web Services

Conceptos

Obtener acceso a la API de SOAP