C#/VB.NET: agregar, responder o eliminar comentarios en Word

2023-09-27 06:34:16 zaki zou

La función de comentarios en Microsoft Word proporciona una excelente manera para que las personas agreguen sus ideas u opiniones a un documento de Word sin tener que cambiar o interrumpir el contenido del documento. Si alguien comenta un documento, el autor del documento u otros usuarios pueden responder al comentario para conversar con él, incluso si no están viendo el documento al mismo tiempo. Este artículo demostrará cómo agregue, responda o elimine comentarios en Word en C# y VB.NET usando la biblioteca Spire.Doc for .NET.

Instalar Spire.Doc for .NET

Para empezar, debe agregar los archivos DLL incluidos en el paquete Spire.Doc for .NET como referencias en su proyecto .NET. Los archivos DLL se pueden descargar desde este enlace o instalar a través de NuGet.

PM> Install-Package Spire.Doc

Agregar un comentario al párrafo en Word en C# y VB.NET

Spire.Doc for .NET provides the proporciona el método Paragraph.AppendComment() para agregar un comentario a un párrafo específico. Los siguientes son los pasos detallados:

  • Inicialice una instancia de la clase Documento.
  • Cargue un documento de Word utilizando el método Document.LoadFromFile().
  • Acceda a una sección específica del documento por su índice a través de la propiedad Document.Sections[int].
  • Acceda a un párrafo específico en la sección por su índice a través de la propiedad Sección.Paragraphs[int].
  • Agregue un comentario al párrafo usando el método Paragraph.AppendComment().
  • Establezca el autor del comentario a través de la propiedad Comment.Format.Author.
  • Guarde el documento resultante utilizando el método Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    using Spire.Doc.Documents;
    using Spire.Doc.Fields;
    
    namespace AddComments
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Initialize an instance of the Document class
                Document document = new Document();
                //Load a Word document
                document.LoadFromFile(@"Sample.docx");
    
                //Get the first section in the document
                Section section = document.Sections[0];
    
                //Get the first paragraph in the section
                Paragraph paragraph = section.Paragraphs[0];
                //Add a comment to the paragraph
                Comment comment = paragraph.AppendComment("This comment is added using Spire.Doc for .NET.");
                //Set comment author
                comment.Format.Author = "Eiceblue";
                comment.Format.Initial = "CM";
    
                //Save the result document
                document.SaveToFile("AddCommentToParagraph.docx", FileFormat.Docx2013);
                document.Close();
            }
        }
    }

C#/VB.NET: Add, Reply to or Delete Comments in Word

Agregar un comentario al texto en Word en C# y VB.NET

El método Paragraph.AppendComment() se utiliza para agregar comentarios a un párrafo completo. De forma predeterminada, las marcas de comentario se colocarán al final del párrafo. Para agregar un comentario a un texto específico, debe buscar el texto usando el método Document.FindString() y luego colocar las marcas de comentario al principio y al final del texto. Los siguientes son los pasos detallados:

  • Inicialice una instancia de la clase Documento.
  • Cargue un documento de Word utilizando el método Document.LoadFromFile().
  • Busque el texto específico en el documento utilizando el método Document.FindString().
  • Cree una marca de inicio de comentario y una marca de final de comentario, que se colocarán al principio y al final del texto encontrado respectivamente.
  • Inicialice una instancia de la clase Comentario para crear un nuevo comentario. Luego configure el contenido y el autor del comentario.
  • Obtenga el párrafo propietario del texto encontrado. Luego agregue el comentario al párrafo como un objeto secundario.
  • Inserte la marca de inicio del comentario antes del rango de texto y la marca de fin del comentario después del rango de texto.
  • Guarde el documento resultante utilizando el método Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    using Spire.Doc.Documents;
    using Spire.Doc.Fields;
    
    namespace AddCommentsToText
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Initialize an instance of the Document class
                Document document = new Document();
                //Load a Word document
                document.LoadFromFile(@"CommentTemplate.docx");
    
                //Find a specific string
                TextSelection find = document.FindString("Microsoft Office", false, true);
    
                //Create the comment start mark and comment end mark
                CommentMark commentmarkStart = new CommentMark(document);
                commentmarkStart.Type = CommentMarkType.CommentStart;
                CommentMark commentmarkEnd = new CommentMark(document);
                commentmarkEnd.Type = CommentMarkType.CommentEnd;
    
                //Create a comment and set its content and author
                Comment comment = new Comment(document);
                comment.Body.AddParagraph().Text = "Developed by Microsoft.";
                comment.Format.Author = "Shaun";
    
                //Get the found text as a single text range
                TextRange range = find.GetAsOneRange();
    
                //Get the owner paragraph of the text range
                Paragraph para = range.OwnerParagraph;
    
                //Add the comment to the paragraph
                para.ChildObjects.Add(comment);
    
                //Get the index of text range in the paragraph
                int index = para.ChildObjects.IndexOf(range);
    
                //Insert the comment start mark before the text range
                para.ChildObjects.Insert(index, commentmarkStart);
                //Insert the comment end mark after the text range
                para.ChildObjects.Insert(index + 2, commentmarkEnd);
    
                //Save the result document
                document.SaveToFile("AddCommentForText.docx", FileFormat.Docx2013);
                document.Close();
            }
        }
    }

C#/VB.NET: Add, Reply to or Delete Comments in Word

Responder a un comentario en Word en C# y VB.NET

Para agregar una respuesta a un comentario existente, puede utilizar el método Comment.ReplyToComment(). Los siguientes son los pasos detallados:

  • Inicialice una instancia de la clase Documento.
  • Cargue un documento de Word utilizando el método Document.LoadFromFile().
  • Obtenga un comentario específico en el documento a través de la propiedad Document.Comments[int].
  • Inicialice una instancia de la clase Comentario para crear un nuevo comentario. Luego configure el contenido y el autor del comentario.
  • Agregue el nuevo comentario como respuesta al comentario específico utilizando el método Comment.ReplyToComment().
  • Guarde el documento resultante utilizando el método Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    using Spire.Doc.Fields;
    
    namespace ReplyToComments
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Initialize an instance of the Document class
                Document document = new Document();
                //Load a Word document
                document.LoadFromFile(@"AddCommentToParagraph.docx");
    
                //Get the first comment in the document
                Comment comment1 = document.Comments[0];
    
                //Create a new comment and specify its author and content
                Comment replyComment1 = new Comment(document);
                replyComment1.Format.Author = "Michael";
                replyComment1.Body.AddParagraph().AppendText("Spire.Doc is a wonderful Word library.");
    
                //Add the comment as a reply to the first comment
                comment1.ReplyToComment(replyComment1);
    
                //Save the result document
                document.SaveToFile("ReplyToComment.docx", FileFormat.Docx2013);
                document.Close();
            }
        }
    }

C#/VB.NET: Add, Reply to or Delete Comments in Word

Eliminar comentarios en Word en C# y VB.NET

Spire.Doc for .NET ofrece el método Document.Comments.RemoveAt(int) para eliminar un comentario específico de un documento de Word y el método Document.Comments.Clear() para eliminar todos los comentarios de un documento de Word. Los siguientes son los pasos detallados:

  • Inicialice una instancia de la clase Documento.
  • Cargue un documento de Word utilizando el método Document.LoadFromFile().
  • Elimine un comentario específico o todos los comentarios en el documento utilizando el método Document.Comments.RemoveAt(int) o el método Document.Comments.Clear().
  • Guarde el documento resultante utilizando el método Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace DeleteComments
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Initialize an instance of the Document class
                Document document = new Document();
                //Load a Word document
                document.LoadFromFile(@"AddCommentToParagraph.docx");
    
                //Delete the first comment in the document
                document.Comments.RemoveAt(0);
    
                //Delete all comments in the document
                //document.Comments.Clear();
    
                //Save the result document
                document.SaveToFile("DeleteComment.docx", FileFormat.Docx2013);
                document.Close();
            }
        }
    }

C#/VB.NET: Add, Reply to or Delete Comments in Word

Solicite una licencia temporal

Si desea eliminar el mensaje de evaluación de los documentos generados o deshacerse de las limitaciones de la función, por favor solicitar una licencia de prueba de 30 días para ti.

Ver también