プログラムを使用してページに Excel Web Access Web パーツを追加するProgrammatically add an Excel Web Access Web Part to a page

次の使用例は、プログラムを使用して Excel Web Access Web パーツを SharePoint ページに追加する方法を示しています。また、プログラムを使用して Excel Web Access Web パーツに Excel ブックを表示する方法も示します。This example shows how to programmatically add an Excel Web Access Web Part to a SharePoint page. It also shows you how to display an Excel workbook programmatically in an Excel Web Access Web Part.

次のプロジェクトでは、Microsoft Visual Studio を使用します。The following project uses Microsoft Visual Studio.

注意

使用する Visual Studio のバージョンと Visual Studio の統合開発環境 (IDE) 設定によって、Visual Studio プロジェクトを作成するためのプロセスと手順は、このトピックに示す手順と若干異なる可能性があります。Depending on the Visual Studio version and the Visual Studio integrated development environment (IDE) settings that you are using, the process and steps to create a Visual Studio project could be slightly different from the procedures shown in this topic.

注意

ここでは、事前に SharePoint ドキュメント ライブラリを作成し、信頼できる場所として既に設定してあることを想定しています。It is assumed that you have already created a SharePoint document library and made it a trusted location. 詳細については、「方法: 場所を信頼する」を参照してください。For more information, see How to: Trust a Location.

参照の追加Adding a Reference

次の手順では、Microsoft.Office.Excel.WebUI.dll を見つけて参照を追加する方法を示します。この手順は、Microsoft.Office.Excel.WebUI.Internal.dll と Microsoft.SharePoint.dll にも繰り返します。The following steps show how to locate Microsoft.Office.Excel.WebUI.dll and how to add a reference to it. Repeat for Microsoft.Office.Excel.WebUI.Internal.dll and Microsoft.SharePoint.dll.

注意

ここでは、Microsoft.Office.Excel.WebUI.dll と Microsoft.Office.Excel.WebUI.Internal.dll がグローバル アセンブリ キャッシュから任意のフォルダーにコピーされていると仮定します。It is assumed that you have already copied Microsoft.Office.Excel.WebUI.dll and Microsoft.Office.Excel.WebUI.Internal.dll from the global assembly cache to a folder of your choice. Microsoft.Office.Excel.WebUI.dll と Microsoft.Office.Excel.WebUI.Internal.dll を見つけてコピーする方法の詳細については、「方法: Microsoft.Office.Excel.WebUI.dll と Microsoft.Office.Excel.WebUI.Internal.dll の場所を見つけてコピーする」を参照してください。For more information about how to locate and copy Microsoft.Office.Excel.WebUI.dll and Microsoft.Office.Excel.WebUI.Internal.dll, see How to: Locate and Copy Microsoft.Office.Excel.WebUI.dll and Microsoft.Office.Excel.WebUI.Internal.dll.

Microsoft.Office.Excel.WebUI.dll への参照を追加するにはTo add a reference to Microsoft.Office.Excel.WebUI.dll

  1. [ プロジェクト] メニューで、[ 参照の追加] をクリックします。On the Project menu, click Add Reference.

  2. [参照の追加] ダイアログ ボックスで、[参照] をクリックします。In the Add Reference dialog box, click Browse.

    注意

    [参照の追加] ダイアログ ボックスは、[ソリューション エクスプローラー] ウィンドウの [参照] を右クリックして [参照の追加] を選択することで開くこともできます。You can also open the Add Reference dialog box in the Solution Explorer pane by right-clicking References and selecting Add Reference.

  3. Microsoft.Office.Excel.WebUI.dll の場所を参照します。Browse to the location of Microsoft.Office.Excel.WebUI.dll.

  4. Microsoft.Office.Excel.WebUI.dll を選択してから [ OK] をクリックします。Select Microsoft.Office.Excel.WebUI.dll, and then click OK.

  5. [ 参照の追加] をクリックします。Microsoft.Office.Excel.WebUI.dll への参照がプロジェクトに追加されます。Click Add Reference. A reference to Microsoft.Office.Excel.WebUI.dll is added to your project.

Web パーツのインスタンスの作成Instantiating a Web Part

Excel Web Access Web パーツのインスタンスを作成するにはTo instantiate the Excel Web Access Web Part

  1. この名前空間の型を使用する際、完全修飾しなくてもよいように、Microsoft.Office.Excel.WebUI 名前空間をディレクティブとしてコードに追加します。Add the Microsoft.Office.Excel.WebUI namespace as a directive to your code, so that when you use the types in this namespace, you do not need to fully qualify them:

using Microsoft.Office.Excel.WebUI;
  Imports Microsoft.Office.Excel.WebUI
  1. 次のように、Excel Web Access Web パーツのインスタンスを作成して初期化します。Instantiate and initialize the Excel Web Access Web Part, as follows:

 ExcelWebRenderer ewaWebPart = new ExcelWebRenderer();

Dim ewaWebPart As New ExcelWebRenderer()

プログラムを使用してブックを表示するにはTo display a workbook programmatically

  1. この例では、 AddWebPart メソッドは、パスを引数として Excel ブックの場所に取り込みます。ユーザーは、Windows フォームのテキスト ボックスに入力し、ボタンをクリックして、パスを指定します。In this example, the AddWebPart method takes in the path to an Excel workbook location as an argument. The user provides the path by typing in a Windows Forms text box and clicking a button.

    サンプル コードの提供者: Daniel Mullowney (Microsoft Corporation)Sample code provided by: Daniel Mullowney, Microsoft Corporation


public bool AddWebPart(string sitename, string book)
{
...
}
            private void AddEWAButton_Click(object sender, 
                EventArgs e)
            {
                siteurl = textBox1.Text;
                bookuri = textBox2.Text;
                succeeded = AddWebPart(siteurl, bookuri);
                if (succeeded)
                {
                    MessageBox.Show(
                        success,
                        appname,
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information);
                    progressBar1.Value = 1;
                }
            }

Public Function AddWebPart(ByVal sitename As String, ByVal book As String) As Boolean
...
End Function
Private Sub AddEWAButton_Click(ByVal sender As Object, ByVal e As EventArgs)
        siteurl = textBox1.Text
        bookuri = textBox2.Text
        succeeded = AddWebPart(siteurl, bookuri)
        If succeeded Then
            MessageBox.Show(success, appname, MessageBoxButtons.OK, MessageBoxIcon.Information)
            progressBar1.Value = 1
        End If
End Sub
> **Important:**
  > Ensure that the location where the workbook is saved is a trusted location. 
  1. 次に示すコードを使用すると、プログラムで Excel ブックを表示できます。You can display an Excel workbook programmatically by using the following code.

    サンプル コードの提供者: Daniel Mullowney (Microsoft Corporation)Sample code provided by: Daniel Mullowney, Microsoft Corporation


...
// Instantiate Excel Web Access web part.
// Add an Excel Web Access web part in a shared view.
ExcelWebRenderer ewaWebPart = new ExcelWebRenderer();
ewaWebPart.WorkbookUri = book;
progressBar1.PerformStep();

try
{
    webPartManager.AddWebPart(ewaWebPart, "Left", 0);
}
catch (Exception exc)
{
    MessageBox.Show(
        addWebPartError + "\\n" + exc.Message,
        appName,
        MessageBoxButtons.OK,
        MessageBoxIcon.Asterisk);
    progressBar1.Value = 1;
    return b;

'Instantiate Excel Web Access web part.
'Add an Excel Web Access web part in a shared view.
Dim ewaWebPart As New ExcelWebRenderer()
ewaWebPart.WorkbookUri = book
progressBar1.PerformStep()

Try
    webPartManager.AddWebPart(ewaWebPart, "Left", 0)
Catch exc As Exception
    MessageBox.Show(addWebPartError & vbLf & exc.Message, appName, 
        MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
    progressBar1.Value = 1
    Return b
End Try

Example

次の使用例は、ユーザーがプログラムを使用して SharePoint サイトに情報を入力し、信頼できる場所に保存された Excel ブックを表示できるようにする Windows フォーム アプリケーションです。このアプリケーションは、プログラムを使用して指定されたサイトの default.aspx ページに Excel Web Access Web パーツを作成し、指定された Excel ブックを表示します。The following example is a Windows Forms application that enables a user to enter information on a SharePoint site and display an Excel workbook saved in a trusted location programmatically. It programmatically creates an Excel Web Access Web Part on the default.aspx page of the specified site and displays the specified Excel workbook.

コードのサンプルは、前の手順で説明した使用例のファイル Form1.cs および Form1.vb のコードです。サンプル コードでは、2 つのテキスト ボックス、進行状況バー、およびボタンを使用します。コードは、Windows フォーム プロジェクトの一部に過ぎません。たとえば、フォームのレイアウトに関連するコードは示されていません。The code sample is the code from the Form1.cs and Form1.vb example files described in the previous procedures. The code sample uses two text boxes, a progress bar, and a button. The code is only a portion of the Windows Forms project. For example, the code involving the layout of the form is not shown.

サンプル コードの提供者: Daniel Mullowney (Microsoft Corporation)Sample code provided by: Daniel Mullowney, Microsoft Corporation


namespace AddEWATool
{
    using System;
    using System.Windows.Forms;
    using Microsoft.Office.Excel.WebUI;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.WebPartPages;

    /// <summary>
    /// Form1 class derived from System.Windows.Forms.
    /// </summary>
    public partial class Form1 : Form
    {
        private string appName = "AddEWATool";
        private string specifyInputError = "Please add a site URL, for example: http://myserver/site/";
        private string openSiteError = "There was a problem with the site name. Please check that the site exists.";
        private string addWebPartError = "There was a problem adding the web part.";
        private string successMessage = "web part successfully added.";

        /// <summary>
        /// Add the Excel Web Access web part to the Default.aspx page of the specified site.
        /// </summary>
        /// <param name="siteName">URL of the SharePoint site</param>
        /// <param name="book">URI to the workbook</param>
        /// <returns>Returns true if the WebPart was successfully added; otherwise, false.</returns>
        public bool AddWebPart(string siteName, string book)
        {
            SPSite site = null;
            SPWeb targetWeb = null;
            SPLimitedWebPartManager webPartManager = null;

            bool b = false;
            progressBar1.Visible = true;
            progressBar1.Minimum = 1;
            progressBar1.Maximum = 4;
            progressBar1.Value = 1;
            progressBar1.Step = 1;

            if (String.IsNullOrEmpty(siteName))
            {
                MessageBox.Show(
                    specifyInputError,
                    appName,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Asterisk);
                return b;
            }

            try
            {
                try
                {
                    site = new SPSite(siteName);
                    targetWeb = site.OpenWeb();
                }
                catch (Exception exc)
                {
                    MessageBox.Show(
                        openSiteError + "\\n" + exc.Message,
                        appName,
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Asterisk);
                    progressBar1.Value = 1;
                    return b;
                }

                progressBar1.PerformStep();

                try
                {
                    // Get the shared web part manager on the Default.aspx page.
                    webPartManager = targetWeb.GetLimitedWebPartManager(
                        "Default.aspx",
                        System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
                }
                catch (Exception exc)
                {
                    MessageBox.Show(
                        openSiteError + "\\n" + exc.Message,
                        appName,
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Asterisk);
                    progressBar1.Value = 1;
                    return b;
                }

                progressBar1.PerformStep();

                // Instantiate Excel Web Access web part.
                // Add an Excel Web Access web part in a shared view.
                ExcelWebRenderer ewaWebPart = new ExcelWebRenderer();
                ewaWebPart.WorkbookUri = book;
                progressBar1.PerformStep();

                try
                {
                    webPartManager.AddWebPart(ewaWebPart, "Left", 0);
                }
                catch (Exception exc)
                {
                    MessageBox.Show(
                        addWebPartError + "\\n" + exc.Message,
                        appName,
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Asterisk);
                    progressBar1.Value = 1;
                    return b;
                }
            }
            finally
            {
                if (site != null)
                {
                    site.Dispose();
                }

                if (targetWeb != null)
                {
                    targetWeb.Dispose();
                }

                if (webPartManager != null)
                {
                    webPartManager.Dispose();
                }
            }

            progressBar1.PerformStep();
            b = true;
            return b;
        }

        /// <summary>
        /// AddEWAButton click handler.
        /// </summary>
        /// <param name="sender">caller</param>
        /// <param name="e">event</param>
        private void AddEWAButton_Click(object sender, EventArgs e)
        {
            string siteUrl = textBox1.Text;
            string bookUri = textBox2.Text;
            bool succeeded = AddWebPart(siteUrl, bookUri);
            if (succeeded)
            {
                MessageBox.Show(
                    successMessage,
                    appName,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
                progressBar1.Value = 1;
            }
        }
    }
}

Imports System
Imports System.Windows.Forms
Imports Microsoft.Office.Excel.WebUI
Imports Microsoft.SharePoint
Imports Microsoft.SharePoint.WebPartPages

Namespace AddEWATool
    ''' <summary>
    ''' Form1 class derived from System.Windows.Forms.
    ''' </summary>
    Partial Public Class Form1
        Inherits Form

        Private appName As String = "AddEWATool"
        Private specifyInputError As String = "Please add a site URL, for example, http://myserver/site/"
        Private openSiteError As String = "There was a problem with the site name. Please check that the site exists."
        Private addWebPartError As String = "There was a problem adding the web part."
        Private successMessage As String = "web part successfully added."

        ''' <summary>
        ''' Add the Excel Web Access web part to the Default.aspx page of the specified site.
        ''' </summary>
        ''' <param name="siteName">URL of the SharePoint site</param>
        ''' <param name="book">URI to the workbook</param>
        ''' <returns>Returns true if the WebPart was successfully added; otherwise, false.</returns>
        Public Function AddWebPart(ByVal siteName As String, ByVal book As String) As Boolean
            Dim site As SPSite = Nothing
            Dim targetWeb As SPWeb = Nothing
            Dim webPartManager As SPLimitedWebPartManager = Nothing

            Dim b As Boolean = False
            progressBar1.Visible = True
            progressBar1.Minimum = 1
            progressBar1.Maximum = 4
            progressBar1.Value = 1
            progressBar1.Step = 1

            If String.IsNullOrEmpty(siteName) Then
                MessageBox.Show(specifyInputError, appName, MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
                Return b
            End If

            Try
                Try
                    site = New SPSite(siteName)
                    targetWeb = site.OpenWeb()
                Catch exc As Exception
                    MessageBox.Show(openSiteError &amp; vbLf &amp; exc.Message, appName, MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
                    progressBar1.Value = 1
                    Return b
                End Try

                progressBar1.PerformStep()

                Try
                    ' Get the shared web part manager on the Default.aspx page.
                    webPartManager = targetWeb.GetLimitedWebPartManager( _
                            "Default.aspx", _
                            System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared)
                Catch exc As Exception
                    MessageBox.Show(openSiteError &amp; vbLf &amp; exc.Message, appName, MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
                    progressBar1.Value = 1
                    Return b
                End Try

                progressBar1.PerformStep()

                'Instantiate Excel Web Access web part.
                'Add an Excel Web Access web part in a shared view.
                Dim ewaWebPart As New ExcelWebRenderer()
                ewaWebPart.WorkbookUri = book
                progressBar1.PerformStep()

                Try
                    webPartManager.AddWebPart(ewaWebPart, "Left", 0)
                Catch exc As Exception
                    MessageBox.Show(addWebPartError &amp; vbLf &amp; exc.Message, appName, MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
                    progressBar1.Value = 1
                    Return b
                End Try
            Finally
                If Not IsNothing(site) Then
                    site.Dispose()
                End If

                If Not IsNothing(targetWeb) Then
                    targetWeb.Dispose()
                End If

                If Not IsNothing(webPartManager) Then
                    webPartManager.Dispose()
                End If
            End Try

            progressBar1.PerformStep()
            b = True
            Return b
        End Function

        ''' <summary>
        ''' AddEWAButton click handler.
        ''' </summary>
        ''' <param name="sender">caller</param>
        ''' <param name="e">event</param>
        Private Sub AddEWAButton_Click(ByVal sender As Object, ByVal e As EventArgs)
            Dim siteUrl As String = textBox1.Text
            Dim bookUri As String = textBox2.Text
            Dim succeeded As Boolean = AddWebPart(siteUrl, bookUri)
            If succeeded Then
                MessageBox.Show(successMessage, appName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                progressBar1.Value = 1
            End If
        End Sub
    End Class
End Namespace


堅牢なプログラミングRobust programming

ご使用の Excel ブックは信頼できる場所にある必要があります。The Excel workbook that you are using must be in a trusted location.

関連項目See also

タスクTasks

方法: Microsoft.Office.Excel.WebUI.dll および Microsoft.Office.Excel.WebUI.Internal.dll を検索してコピーするHow to: Locate and Copy Microsoft.Office.Excel.WebUI.dll and Microsoft.Office.Excel.WebUI.Internal.dll

概念Concepts

Excel Services のアラートExcel Services Alerts

Excel Services の既知の問題およびヒントExcel Services Known Issues and Tips