範囲の値を設定する

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

適用対象: SharePoint Server 2010

Excel Web Services では、Excel ブックに値を設定するために、SetCell、SetCellA1、SetRange、および SetRangeA1 の 4 つのメソッドが公開されています。

注意

Excel Web Services を使用して範囲に値を設定するなどの変更をブックに加えた場合、ブックに対する変更が保持されるのは、その特定のセッションの間だけです。変更内容が元のブックに保存されることはありません。現在のブックのセッションが終了すると (たとえば CloseWorkbook メソッドを呼び出したり、セッションがタイムアウトした場合)、加えた変更は失われます。

ブックに対して加えた変更を保存する必要がある場合は、GetWorkbook メソッドを使用し、次に保存先ファイル ストアの API を使用するとブックを保存できます。詳細については、「[方法] ブック全体またはスナップショットを取得する」と「[方法] ブックを保存する」を参照してください。

1 つのセルの値を設定する場合は、SetCell メソッドや SetCellA1 メソッドを使用します。たとえば "D3:G5" のような範囲の参照、1 つのセルより大きい名前付き範囲を渡すなど、一定範囲のセルに値を設定しようとすると、メソッドの呼び出しは失敗します。セルの範囲に値を設定する必要がある場合は、代わりに SetRange メソッドと SetRangeA1 メソッドを使用します。

A1 サフィックスが付いているメソッド (SetCellA1 と SetRangeA1) は、このサフィックスが付いていないメソッド (SetCell と SetRange) とは異なる座標系を使用します。範囲の参照 (H8, A3:D5、Sheet2!A12:G18 など) のような Excel スタイルのセル参照や名前付きの範囲を使用する場合は、A1 サフィックスが付いたメソッドを使用する必要があります。これらのメソッドでは、シートの名前や範囲を渡すことができます。

数値による座標系を使って Excel の範囲にアクセスする場合は、A1 サフィックスが付かないメソッドを使用する必要があります。一連のセルをループで繰り返すコードを使用する場合、またはアルゴリズムの一部として範囲の座標が動的に計算される場合は、範囲の座標を使用する方が簡単です。

セルの行および列の座標は 0 から始まります。このため、下の例のように "0,0" を指定すると、セル A1 が返されます。

// Call the SetCell method to set a value, 8, into a cell.
// The cell is in the first row and first column; that is, cell A1.
xlservice.SetCell(sessionId, sheetName, 0, 0, 8);
' Call the SetCell method to set a value, 8, into a cell.
' The cell is in the first row and first column; that is, cell A1.
xlservice.SetCell(sessionId, sheetName, 0, 0, 8)

複数の隣接するセルから値を取得する場合は、SetCell メソッドの呼び出しを複数行う代わりに、SetRange メソッドを使用することを検討してください。これによりサーバーへの往復回数は、複数回ではなく 1 回になります。したがって、場合によっては、SetCell メソッドの代わりに SetRange メソッドを使用することで、明らかなパフォーマンスの向上が得られる可能性があります。

SetRange メソッドや SetRangeA1 メソッドを使用してセルの範囲に値を設定するときには、オブジェクト配列 (C# では object[]、Visual Basic .NET では Object ()) を使用します。オブジェクト配列は実際にはジャグ配列です。配列内の各エントリは、セルを表すオブジェクトの別の配列になります。ジャグ配列の詳細については、「Jagged Arrays (C# Programming Guide) (英語)」(https://msdn.microsoft.com/ja-jp/library/2s05feca.aspx) (英語) を参照してください。

SetCell メソッドと SetRange メソッドを使用して値を設定するには

  1. 数値の範囲の座標を使い、開いたブックのセルに値を設定する場合は、SetCell メソッドを使用します。

    // Instantiate the Web service and make a status array object.
    ExcelService xlservice = new ExcelService();
    Status[] outStatus;
    RangeCoordinates rangeCoordinates = new RangeCoordinates();
    string sheetName = "Sheet2";
    
    // Set the path to a workbook.
    // The workbook must be in a trusted location.
    string targetWorkbookPath = "http://myserver02/example/Shared%20Documents/Book1.xlsx";
    
    // Set credentials for requests.
    xlservice.Credentials = System.Net.CredentialCache.DefaultCredentials;
    
    // Call the open workbook, and point to the trusted 
    // location of the workbook to open.
    string sessionId = xlservice.OpenWorkbook(targetWorkbookPath, "en-US", "en-US", out outStatus);
    
    // Call the SetCell method to set the cell's value to 28.
    // The cell is in the ninth row and second column, which is cell B9.
    xlservice.SetCell(sessionId, sheetName, 8, 1, 28);
    
    ' Instantiate the Web service and make a status array object.
    Dim xlservice As New ExcelService()
    Dim outStatus() As Status
    Dim rangeCoordinates As New RangeCoordinates()
    Dim sheetName As String = "Sheet2"
    
    ' Set the path to a workbook.
    ' The workbook must be in a trusted location.
    Dim targetWorkbookPath As String = "http://myserver02/example/Shared%20Documents/Book1.xlsx"
    
    ' Set credentials for requests.
    xlservice.Credentials = System.Net.CredentialCache.DefaultCredentials
    
    ' Call the open workbook, and point to the trusted 
    ' location of the workbook to open.
    Dim sessionId As String = xlservice.OpenWorkbook(targetWorkbookPath, "en-US", "en-US", outStatus)
    
    ' Call the SetCell method to set the cell's value to 28.
    ' The cell is in the ninth row and second column, which is cell B9.
    xlservice.SetCell(sessionId, sheetName, 8, 1, 28)
    
  2. 数値の範囲の座標を使い、開いたブックの特定の範囲に値を設定する場合は、SetRange メソッドを使用します。

    // Instantiate the Web service and make a status array object.
    ExcelService xlservice = new ExcelService();
    Status[] outStatus;
    RangeCoordinates rangeCoordinates = new RangeCoordinates();
    
    ...
    private void Form1_Load(object sender, EventArgs e)
    {
    ...
    ...
    //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;
    ...
    ...
    }
    private void SetRangeButton_Click(object sender, EventArgs e)
    {
    object[] values = new object[rangeCoordinates.Height];
    string[] fieldValues =    
        SetRangeTextBox.Text.Split((",").ToCharArray());
    
    if (fieldValues.Length != rangeCoordinates.Height * 
    rangeCoordinate.Width)
        {
            throw new Exception("The number of inputs (" + 
                fieldValues.Length + ") does not match" +
                " the product of Height (" +             rangeCoordinates.Height + ") and Width (" + 
                rangeCoordinates.Width + ")");
        }
    
    for (int i = 0; i < rangeCoordinates.Height; i++)
        {
            object[] currentRow = 
                new object[rangeCoordinates.Width];
            for (int j = 0; j < rangeCoordinates.Width; j++)
            {
                currentRow[j] = fieldValues[i *             rangeCoordinates.Width + j];
            }
            values[i] = currentRow;
        }
    
    SetStatusText("Waiting for SetRange...");
    outStatus = xlservice.SetRange(
        sessionID, SheetNameTextBox.Text, 
        rangeCoordinates, values);
    }
    catch (SoapException exc)
    {
    StopTimer("SetRange");
    GenerateErrorMessage("SetRange", exc);
    }
    catch (Exception exc)
    {
    StopTimer("SetRange");
    GenerateToolErrorMessage("While calling SetRange", exc);
    }
    }
    
    ' Instantiate the Web service and make a status array object.
    Private xlservice As New ExcelService()
    Private outStatus() As Status
    Private rangeCoordinates As New RangeCoordinates()
    
    ...
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
    ...
    ...
    '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))
    ...
    ...
    End Sub
    Private Sub SetRangeButton_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim values(rangeCoordinates.Height - 1) As Object
    Dim fieldValues() As String = SetRangeTextBox.Text.Split((",").ToCharArray())
    
    If fieldValues.Length <> rangeCoordinates.Height * rangeCoordinate.Width Then
            Throw New Exception("The number of inputs (" & fieldValues.Length & ") does not match" & " the product of Height (" & rangeCoordinates.Height & ") and Width (" & rangeCoordinates.Width & ")")
    End If
    
    For i As Integer = 0 To rangeCoordinates.Height - 1
            Dim currentRow(rangeCoordinates.Width - 1) As Object
            For j As Integer = 0 To rangeCoordinates.Width - 1
                currentRow(j) = fieldValues(i * rangeCoordinates.Width + j)
            Next j
            values(i) = currentRow
    Next i
    Try
    SetStatusText("Waiting for SetRange...")
    outStatus = xlservice.SetRange(sessionID, SheetNameTextBox.Text, rangeCoordinates, values)
    Catch exc As SoapException
    StopTimer("SetRange")
    GenerateErrorMessage("SetRange", exc)
    Catch exc As Exception
    StopTimer("SetRange")
    GenerateToolErrorMessage("While calling SetRange", exc)
    End Try
    End Sub
    

SetCellA1 メソッドと SetRangeA1 メソッドを使用して値を設定するには

  1. Excel の "A1" という範囲の指定を使い、開いたブックの特定のセルに値を設定する場合は、SetCellA1 メソッドを使用します。

    // Instantiate the Web service and make a status array object.
    ExcelService xlservice = new ExcelService();
    Status[] outStatus;
    
    xlservice.SetCellA1(sessionId, String.Empty, "InterestRateParam", 8);
    
    ' Instantiate the Web service and make a status array object.
    Dim xlservice As New ExcelService()
    Dim outStatus() As Status
    
    xlservice.SetCellA1(sessionId, String.Empty, "InterestRateParam", 8)
    
  2. Excel の "A1" という範囲の指定を使い、開いたブックの特定の範囲に値を設定する場合は、SetRangeA1 メソッドを使用します。

    // Instantiate the Web service and make a status array object.
    ExcelService xlservice = new ExcelService();
    Status[] outStatus;
    ...
    
    void SetRangeA1Button_ServerClick(object sender, EventArgs e)
    {
        int height, width;
        CalculateHeightAndWidth(RangeNameTextBox5.Value.Trim(), 
            out height, out width);
    
        object[] values = new object[height];
        string[] fieldValues = 
            RangeValuesTextBox1.Value.Split((",").ToCharArray());
        if (fieldValues.Length != height * width)
        {
            throw new Exception("The number of inputs (" + 
                fieldValues.Length + ") does not match" +
                " the product of Height (" + height + ") and 
                Width (" + width + ")");
        }
    
        for (int i = 0; i < height; i++)
        {
            object[] currentRow = new object[width];
            for (int j = 0; j < width; j++)
            {
                currentRow[j] = fieldValues[i * width + j];
            }
            values[i] = currentRow;
        }
        try
        {
            xlservice.SetRangeA1(SessionIDTextBox.Value, 
                SheetNameTextBox1.Value,RangeNameTextBox5.Value,
                values, out outStatus);
        }
        catch (SoapException exc)
        {
            ExceptionTextBox1.Value = exc.Message;
        }
    
    }
    
    ' Instantiate the Web service and make a status array object.
    Private xlservice As New ExcelService()
    Private outStatus() As Status
    ...
    
    Private Sub SetRangeA1Button_ServerClick(ByVal sender As Object, ByVal e As EventArgs)
        Dim height, width As Integer
        CalculateHeightAndWidth(RangeNameTextBox5.Value.Trim(), height, width)
    
        Dim values(height - 1) As Object
        Dim fieldValues() As String = RangeValuesTextBox1.Value.Split((",").ToCharArray())
        If fieldValues.Length <> height * width Then
            Throw New Exception("The number of inputs (" & fieldValues.Length & ") does not match" & " the product of Height (" & height & ") and Width (" & width & ")")
        End If
    
        For i As Integer = 0 To height - 1
            Dim currentRow(width - 1) As Object
            For j As Integer = 0 To width - 1
                currentRow(j) = fieldValues(i * width + j)
            Next j
            values(i) = currentRow
        Next i
        Try
            xlservice.SetRangeA1(SessionIDTextBox.Value, SheetNameTextBox1.Value,RangeNameTextBox5.Value, values, outStatus)
        Catch exc As SoapException
            ExceptionTextBox1.Value = exc.Message
        End Try
    
    End Sub
    

関連項目

タスク

[方法] 範囲のアドレスとシート名を指定する

[方法] 範囲から値を取得する

[ウォークスルー] Excel Web Services を使用してカスタム アプリケーションを開発する

概念

SOAP API にアクセスする