Procédure : ajouter par programme un composant WebPart Excel Web Access à une page

Dernière modification : jeudi 8 avril 2010

S’applique à : SharePoint Server 2010

Cet exemple montre comment ajouter par programme un composant WebPart Excel Web Access à une page SharePoint. Il montre également comment afficher par programme un classeur Excel dans un composant WebPart Excel Web Access.

Le projet suivant utilise Microsoft Visual Studio.

Notes

En fonction de la version de Visual Studio et des paramètres d’environnement de développement intégré Visual Studio que vous utilisez, le processus et les étapes de création d’un projet Visual Studio peuvent légèrement différer des procédures décrites dans cette rubrique.

Notes

Il est supposé que vous avez déjà créé une bibliothèque de documents SharePoint et que vous l’avez configurée en tant qu’emplacement approuvé. Pour plus d’informations, voir Procédure : Approuver un emplacement.

Ajout d'une référence

Les étapes suivantes indiquent comment rechercher Microsoft.Office.Excel.WebUI.dll et comment ajouter une référence à ce fichier. Procédez de même pour Microsoft.Office.Excel.WebUI.Internal.dll et Microsoft.SharePoint.dll.

Notes

Il est supposé que vous avez déjà copié Microsoft.Office.Excel.WebUI.dll et Microsoft.Office.Excel.WebUI.Internal.dll depuis le Global Assembly Cache vers un dossier de votre choix. Pour plus d’informations sur la recherche et la copie de Microsoft.Office.Excel.WebUI.dll et de Microsoft.Office.Excel.WebUI.Internal.dll, voir Procédure : Rechercher et copier Microsoft.Office.Excel.WebUI.dll et Microsoft.Office.Excel.WebUI.Internal.dll.

Pour ajouter une référence à Microsoft.Office.Excel.WebUI.dll

  1. Sur le menu Projet, cliquez sur Ajouter une référence.

  2. Dans la boîte de dialogue Ajouter une référence, cliquez sur Parcourir.

    Notes

    Vous pouvez aussi ouvrir la boîte de dialogue Ajouter une référence dans le volet Explorateur de solutions en cliquant avec le bouton droit sur Références et en sélectionnant Ajouter une référence.

  3. Accédez à l'emplacement de Microsoft.Office.Excel.WebUI.dll.

  4. Sélectionnez Microsoft.Office.Excel.WebUI.dll, puis cliquez sur OK.

  5. Cliquez sur Ajouter une référence ; une référence à Microsoft.Office.Excel.WebUI.dll est alors ajoutée à votre projet.

Instanciation d'un composant WebPart

Pour instancier le composant WebPart Excel Web Access

  1. Ajoutez l’espace de noms Microsoft.Office.Excel.WebUI en tant que directive à votre code, de façon à ce que, quand vous utilisez les types de cet espace de noms, il ne soit pas nécessaire de les qualifier complètement :

    using Microsoft.Office.Excel.WebUI;
    
    Imports Microsoft.Office.Excel.WebUI
    
  2. Instanciez et initialisez le composant WebPart Excel Web Access comme suit :

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

Pour afficher un classeur par programme

  1. Dans cet exemple, la méthode AddWebPart reçoit le chemin d’accès à un emplacement de classeur Excel en tant qu’argument. L’utilisateur fournit le chemin d’accès en le tapant dans une zone de texte Windows Forms et en cliquant sur un bouton.

    Exemple de code fourni par : 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

    Vérifiez que l’emplacement où le classeur est enregistré est un emplacement approuvé.

  2. Vous pouvez afficher un classeur Excel par programmation à l’aide du code suivant.

    Exemple de code fourni par : 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
    

Exemple

L’exemple suivant est une application Windows Forms qui permet à un utilisateur d’entrer des informations sur un site SharePoint et d’afficher par programmation un classeur Excel enregistré dans un emplacement approuvé. Il crée par programmation un composant WebPart Excel Web Access dans la page default.aspx du site spécifié et affiche le classeur Excel spécifié.

L’exemple de code contient le code des exemples de fichiers Form1.cs et Form1.vb décrits dans les procédures précédentes. L’exemple de code utilise deux zones de texte, une barre de progression et un bouton. Le code n’est qu’une partie du projet Windows Forms ; par exemple, le code impliquant la disposition du formulaire n’est pas indiqué.

Exemple de code fourni par : 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

Programmation fiable

Le classeur Excel que vous utilisez doit se trouver à un emplacement approuvé.

Voir aussi

Tâches

Procédure : Rechercher et copier Microsoft.Office.Excel.WebUI.dll et Microsoft.Office.Excel.WebUI.Internal.dll

Concepts

Excel Services Alerts

Problèmes connus et conseils Excel Services