Share via


Cómo: Crear etiquetas inteligentes con reconocedores personalizados en Excel y .NET Framework 4

En proyectos Excel destinados a .NET Framework 4, puede controlar cómo reconoce Word las etiquetas inteligentes en documentos implementando la interfaz ISmartTagExtension.

Para ejecutar una etiqueta inteligente, los usuarios finales deben tener las etiquetas inteligentes habilitadas en Word o en Excel. Para obtener más información, vea Cómo: Habilitar las etiquetas inteligentes en Word y en Excel.

Se aplica a: la información de este tema se aplica a los proyectos de nivel de documento y los proyectos de nivel de aplicación para Excel 2007. Para obtener más información, vea Características disponibles por aplicación y tipo de proyecto de Office.

Para agregar una etiqueta inteligente con un reconocedor personalizado a un libro de Excel

  1. Cree un proyecto de nivel de documento o de nivel de aplicación para Excel 2007. Para obtener más información, vea Cómo: Crear proyectos de Office en Visual Studio.

  2. Agregue una referencia al ensamblado Microsoft.Office.Interop.SmartTag (versión 12.0.0.0) desde la pestaña .NET del cuadro de diálogo Agregar referencia.

  3. Agregue un archivo de clase al proyecto y cree una clase que implemente la interfaz ISmartTagExtension.

  4. En la nueva clase, cree un objeto SmartTag que representa la etiqueta inteligente y cree uno o más objetos Action que representan las acciones de etiqueta inteligente. Utilice los métodos Globals.Factory.CreateSmartTag y Globals.Factory.CreateAction para crear estos objetos.

  5. Implemente el método Recognize y escriba su propio comportamiento de reconocimiento personalizado. Su implementación debe llamar al método PersistTag del parámetro context para que Excel reconozca la etiqueta inteligente.

  6. Implemente la propiedad ExtensionBase para devolver el objeto SmartTag.

  7. Cree controladores de eventos para responder al evento Click y, opcionalmente, al evento BeforeCaptionShow, de las acciones creadas.

  8. En el archivo de código del documento del libro, agregue la instancia de etiqueta inteligente a la propiedad VstoSmartTags de la clase ThisWorkbook (para un proyecto en el nivel del documento) o la propiedad VstoSmartTags de la clase ThisAddIn (para un proyecto en el nivel de la aplicación).

Ejemplo

En el ejemplo de código siguiente se muestra cómo crear una etiqueta inteligente personalizada en un libro de Excel. En el ejemplo se implementa el método Recognize para reconocer los términos sales y organization de una celda de hoja de cálculo. El método Recognize agrega un par de clave y valor a la colección de propiedades principales de la etiqueta inteligente. El método llama, a continuación, al método PersistTag para reconocer la etiqueta inteligente y guardar la nueva propiedad de etiqueta inteligente. Para probar el ejemplo, escriba las palabras sales y organization en celdas diferentes del libro y, a continuación, pruebe las acciones de la etiqueta inteligente. Una acción muestra el valor de la propiedad correspondiente para el término reconocido y la otra, muestra el espacio de nombres de la etiqueta inteligente y el título.

Imports System
Imports System.Windows.Forms
Imports Microsoft.Office.Interop.SmartTag
Imports Microsoft.Office.Tools.Excel

Public Class CustomSmartTag
    Implements ISmartTagExtension

    ' Declare the smart tag.
    Private smartTagDemo As Microsoft.Office.Tools.Excel.SmartTag

    ' Declare actions for this smart tag.
    WithEvents Action1 As Microsoft.Office.Tools.Excel.Action
    WithEvents Action2 As Microsoft.Office.Tools.Excel.Action

    Public Sub New()
        Me.smartTagDemo = Globals.Factory.CreateSmartTag(
            "https://www.contoso.com/Demo#DemoSmartTag", "Custom Smart Tag", Me)

        Action1 = Globals.Factory.CreateAction("Display property value")
        Action2 = Globals.Factory.CreateAction("Display smart tag details")

        smartTagDemo.Terms.AddRange(New String() {"sales", "organization"})
        smartTagDemo.Actions = New Microsoft.Office.Tools.Excel.Action() {Action1, Action2}
    End Sub

    Private Sub Recognize(ByVal text As String, 
        ByVal site As ISmartTagRecognizerSite, ByVal tokenList As ISmartTagTokenList, 
        ByVal context As SmartTagRecognizeContext) Implements ISmartTagExtension.Recognize

        ' Determine whether each smart tag term exists in the document text.
        Dim Term As String
        For Each Term In smartTagDemo.Terms

            ' Search the cell text for the first instance of 
            ' the current smart tag term.
            Dim index As Integer = context.CellText.IndexOf(Term, 0)

            If (index >= 0) Then

                ' Create a smart tag token and a property bag for the 
                ' recognized term.
                Dim propertyBag As ISmartTagProperties = site.GetNewPropertyBag()

                ' Write a new property value.
                Dim key As String = "Key1"
                propertyBag.Write(key, DateTime.Now)

                ' Attach the smart tag to the term in the document.
                context.PersistTag(propertyBag)

                ' This implementation only finds the first instance
                ' of a smart tag term in the cell. 
                Exit For
            End If
        Next
    End Sub

    ' This action displays the property value for the term.
    Private Sub Action1_Click(ByVal sender As Object,
        ByVal e As Microsoft.Office.Tools.Excel.ActionEventArgs) Handles Action1.Click

        Dim propertyBag As ISmartTagProperties = e.Properties
        Dim key As String = "Key1"
        MessageBox.Show("The corresponding value of " & key & " is: " &
            propertyBag.Read(key))
    End Sub

    ' This action displays smart tag details.
    Private Sub Action2_Click(ByVal sender As Object,
        ByVal e As Microsoft.Office.Tools.Excel.ActionEventArgs) Handles Action2.Click
        MessageBox.Show("The current smart tag caption is '" &
        smartTagDemo.Caption & "'. The current smart tag type is '" &
        smartTagDemo.SmartTagType & "'.")
    End Sub

    Public ReadOnly Property Base() As Microsoft.Office.Tools.Excel.SmartTag
        Get
            Return smartTagDemo
        End Get
    End Property

    Public ReadOnly Property ExtensionBase() As Object Implements ISmartTagExtension.ExtensionBase
        Get
            Return smartTagDemo
        End Get
    End Property
End Class
using System;
using System.Windows.Forms;
using Microsoft.Office.Interop.SmartTag;
using Microsoft.Office.Tools.Excel;

namespace Trin_ExcelDerivedSmartTags4
{
    class CustomSmartTag : ISmartTagExtension
    {
        // Declare the smart tag.
        Microsoft.Office.Tools.Excel.SmartTag smartTagDemo;

        // Declare actions for this smart tag.
        private Microsoft.Office.Tools.Excel.Action Action1;
        private Microsoft.Office.Tools.Excel.Action Action2;

        public CustomSmartTag()
        {
            this.smartTagDemo = Globals.Factory.CreateSmartTag(
                "https://www.contoso.com/Demo#DemoSmartTag", "Custom Smart Tag", this);

            Action1 = Globals.Factory.CreateAction("Display property value");
            Action2 = Globals.Factory.CreateAction("Display smart tag details");

            smartTagDemo.Terms.AddRange(new string[] { "sales", "organization" });
            smartTagDemo.Actions = new Microsoft.Office.Tools.Excel.Action[] { 
                Action1, Action2 };

            Action1.Click += new ActionClickEventHandler(Action1_Click);
            Action2.Click += new ActionClickEventHandler(Action2_Click);
        }

        void ISmartTagExtension.Recognize(string text, ISmartTagRecognizerSite site, 
            ISmartTagTokenList tokenList, SmartTagRecognizeContext context)
        {

            // Determine whether each smart tag term exists in the document text.
            foreach (string term in smartTagDemo.Terms)
            {
                // Search the cell text for the first instance of the current smart tag term.
                int index = context.CellText.IndexOf(term, 0);

                if (index >= 0)
                {
                    // Create a smart tag token and a property bag for the recognized term.
                    ISmartTagProperties propertyBag = site.GetNewPropertyBag();

                    // Write a new property value.                 
                    string key = "Key1";
                    propertyBag.Write(key, DateTime.Now.ToString());

                    // Attach the smart tag to the term in the document
                    context.PersistTag(propertyBag);

                    // This implementation only finds the first instance of a 
                    // smart tag term in the cell. 
                    break;
                }
            }
        }

        // This action displays the property value for the term.
        private void Action1_Click(object sender,
            Microsoft.Office.Tools.Excel.ActionEventArgs e)
        {
            ISmartTagProperties propertyBag = e.Properties;
            string key = "Key1";
            MessageBox.Show("The corresponding value of " + key +
                " is: " + propertyBag.get_Read(key));
        }

        // This action displays smart tag details.
        private void Action2_Click(object sender,
            Microsoft.Office.Tools.Excel.ActionEventArgs e)
        {
            MessageBox.Show("The current smart tag caption is '" +
                smartTagDemo.Caption + "'. The current smart tag type is '" +
                smartTagDemo.SmartTagType + "'.");
        }

        public Microsoft.Office.Tools.Excel.SmartTag Base
        {
            get { return smartTagDemo; }
        }

        public object ExtensionBase
        {
            get { return smartTagDemo; }
        }
    }

Compilar el código

  • En el proyecto, agregue una referencia a la Biblioteca de tipos de Etiquetas inteligentes de Microsoft 2.0 de la ficha COM del cuadro de diálogo Agregar referencia. Compruebe que la propiedad Copy Local de la referencia es false. Si es true, la referencia no se aplica al ensamblado de interoperabilidad primario correcto y se debe instalar el ensamblado de los discos de instalación de Microsoft Office. Para obtener más información, vea Cómo: Instalar ensamblados de interoperabilidad primarios de Office.

  • Coloque el código de ejemplo en un nuevo archivo de clase denominado CustomSmartTag.

  • En C#, cambie el espacio de nombres para que coincida con el nombre del proyecto.

  • Agregue Imports (en Visual Basic) o instrucciones using (en C#) para los espacios de nombres Microsoft.Office.Tools.Excel y Microsoft.Office.Interop.SmartTag en la parte superior del archivo de clases.

  • Agregue el código siguiente al controlador de eventos ThisAddIn_Startup o ThisWorkbook_Startup en su proyecto. Este código agrega la etiqueta inteligente personalizada al libro.

    Me.VstoSmartTags.Add(New CustomSmartTag().Base)
    
    this.VstoSmartTags.Add(new CustomSmartTag().Base);
    

Seguridad

Debe habilitar las etiquetas inteligentes en Excel. No están habilitadas de manera predeterminada. Para obtener más información, vea Cómo: Habilitar las etiquetas inteligentes en Word y en Excel.

Vea también

Tareas

Cómo: Habilitar las etiquetas inteligentes en Word y en Excel

Cómo: Agregar etiquetas inteligentes a documentos de Word

Cómo: Agregar etiquetas inteligentes a libros de Excel

Cómo: Crear etiquetas inteligentes con reconocedores personalizados en Word y .NET Framework 3.5

Tutorial: Crear una etiqueta inteligente usando una personalización de nivel de documento.

Tutorial: Crear una etiqueta inteligente usando un complemento de nivel de aplicación

Conceptos

Arquitectura de las etiquetas inteligentes

Otros recursos

Información general sobre etiquetas inteligentes

Personalización de la interfaz de usuario de Office