Share via


Excel Web Access Web パーツをプログラムによってページに追加する

最終更新日: 2010年4月8日

適用対象: SharePoint Server 2010

この例では、Excel Web Access Web パーツをプログラムによって SharePoint ページに追加する方法を示します。また、Excel ブックをプログラムによって Excel Web Access Web パーツに表示する方法も示します。

以下のプロジェクトでは、Microsoft Visual Studio を使用します。

注意

使用している Visual Studio のバージョンと Visual Studio 統合開発環境 (IDE) の設定によっては、Visual Studio プロジェクトを作成する処理と手順が、このトピックで示すものとわずかに異なる可能性があります。

注意

既に SharePoint ドキュメント ライブラリを作成し、それを信頼できる場所にしたことを前提としています。この詳細については、「[方法] 場所を信頼する」を参照してください。

参照を追加する

次の手順では、Microsoft.Office.Excel.WebUI.dll を検索し、参照を追加する方法を示します。Microsoft.Office.Excel.WebUI.Internal.dll と Microsoft.SharePoint.dll に対して繰り返します。

注意

Microsoft.Office.Excel.WebUI.dll と Microsoft.Office.Excel.WebUI.Internal.dll をグローバル アセンブリ キャッシュから任意のフォルダーに既にコピーしたことを前提としています。Microsoft.Office.Excel.WebUI.dll と Microsoft.Office.Excel.WebUI.Internal.dll を検索し、コピーする方法の詳細については、「[方法] Microsoft.Office.Excel.WebUI.dll と Microsoft.Office.Excel.WebUI.Internal.dll を見つけてコピーする」を参照してください。

Microsoft.Office.Excel.WebUI.dll に参照を追加するには

  1. [プロジェクト] メニューで、[参照の追加] をクリックします。

  2. [参照の追加] ダイアログ ボックスで、[参照] をクリックします。

    注意

    [ソリューション エクスプローラ] ウィンドウで、[参照設定] を右クリックし、[参照の追加] を選択して、[参照の追加] ダイアログ ボックスを開くこともできます。

  3. Microsoft.Office.Excel.WebUI.dll の場所を参照します。

  4. Microsoft.Office.Excel.WebUI.dll を選択し、[OK] をクリックします。

  5. [参照の追加] をクリックします。Microsoft.Office.Excel.WebUI.dll への参照がプロジェクトに追加されます。

Web パーツをインスタンス化する

Excel Web Access Web パーツをインスタンス化するには

  1. Microsoft.Office.Excel.WebUI 名前空間をディレクティブとしてコードに追加し、この名前空間で型を使用するときに、完全修飾名を指定しなくても済むようにします。

    using Microsoft.Office.Excel.WebUI;
    
    Imports Microsoft.Office.Excel.WebUI
    
  2. Excel Web Access Web パーツを次のとおりインスタンス化し、初期化します。

    
     ExcelWebRenderer ewaWebPart = new ExcelWebRenderer();
    
    Dim ewaWebPart As New ExcelWebRenderer()
    

プログラムによってブックを表示するには

  1. 次の例では、AddWebPart メソッドは Excel ブックへのパスを引数としてとります。ユーザーは、Windows フォームのテキスト ボックスに入力し、ボタンをクリックしてパスを指定します。

    サンプル コードの提供者 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
    
    重要重要

    ブックが信頼できる場所に保存されていることを確認します。

  2. 次のコードを使用して、Excel ブックをプログラムによって表示することができます。

    サンプル コードの提供者 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
    

以下の例は、プログラムによって、ユーザーが SharePoint サイトで情報を入力し、信頼できる場所に保存された Excel ブックを表示できるようにする Windows Forms アプリケーションです。またプログラムによって、指定されたサイトの default.aspx ページに Excel Web Access Web パーツを作成し、指定された Excel ブックを表示します。

コード例は、前の手順で説明した Form1.cs と Form1.vb のサンプル ファイルのコードです。コード例では、2 つのテキスト ボックス、1 つの進捗状況バー、および 1 つのボタンを使用します。コードは、Windows Forms プロジェクトの一部です。たとえば、フォームのレイアウトに関連するコードは表示されません。

サンプル コードの提供者 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 & vbLf & 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 & vbLf & 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 & vbLf & 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

堅牢なプログラミング

使用する Excel ブックは信頼できる場所になければなりません。

関連項目

タスク

[方法] Microsoft.Office.Excel.WebUI.dll と Microsoft.Office.Excel.WebUI.Internal.dll を見つけてコピーする

概念

Excel Services の警告

Excel Services に関する既知の問題とヒント