O recurso de comentários do Microsoft Word oferece uma excelente maneira para as pessoas adicionarem seus insights ou opiniões a um documento do Word sem precisar alterar ou interromper o conteúdo do documento. Se alguém comentar um documento, o autor do documento ou outros usuários poderão responder ao comentário para discutir com ele, mesmo que não estejam visualizando o documento ao mesmo tempo. Este artigo demonstrará como adicione, responda ou exclua comentários no Word em C# e VB.NET usando a biblioteca Spire.Doc for .NET.

Instale o Spire.Doc for .NET

Para começar, você precisa adicionar os arquivos DLL incluídos no pacote Spire.Doc for.NET como referências em seu projeto .NET. Os arquivos DLL podem ser baixados deste link ou instalados via NuGet.

PM> Install-Package Spire.Doc

Adicione um comentário ao parágrafo no Word em C# e VB.NET

Spire.Doc for .NET fornece o método Paragraph.AppendComment() para adicionar um comentário a um parágrafo específico. A seguir estão as etapas detalhadas:

  • Inicialize uma instância da classe Document.
  • Carregue um documento do Word usando o método Document.LoadFromFile().
  • Acesse uma seção específica do documento pelo seu índice através da propriedade Document.Sections[int].
  • Acesse um parágrafo específico da seção pelo seu índice através da propriedade Section.Paragraphs[int].
  • Adicione um comentário ao parágrafo usando o método Paragraph.AppendComment().
  • Defina o autor do comentário através da propriedade Comment.Format.Author.
  • Salve o documento resultante usando o 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

Adicione um comentário ao texto no Word em C# e VB.NET

O método Paragraph.AppendComment() é usado para adicionar comentários a um parágrafo inteiro. Por padrão, os comentários serão colocados no final do parágrafo. Para adicionar um comentário a um texto específico, você precisa pesquisar o texto usando o método Document.FindString() e, em seguida, colocar as marcas de comentário no início e no final do texto. A seguir estão as etapas detalhadas:

  • Inicialize uma instância da classe Document.
  • Carregue um documento do Word usando o método Document.LoadFromFile().
  • Encontre o texto específico no documento usando o método Document.FindString().
  • Crie uma marca de início de comentário e uma marca de final de comentário, que serão colocadas no início e no final do texto encontrado, respectivamente.
  • Inicialize uma instância da classe Comment para criar um novo comentário. Em seguida, defina o conteúdo e o autor do comentário.
  • Obtenha o parágrafo do proprietário do texto encontrado. Em seguida, adicione o comentário ao parágrafo como objeto filho.
  • Insira a marca de início do comentário antes do intervalo de texto e a marca de final do comentário após o intervalo de texto.
  • Salve o documento resultante usando o 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 um comentário no Word em C# e VB.NET

Para adicionar uma resposta a um comentário existente, você pode usar o método Comment.ReplyToComment(). A seguir estão as etapas detalhadas:

  • Inicialize uma instância da classe Document.
  • Carregue um documento do Word usando o método Document.LoadFromFile().
  • Obtenha um comentário específico no documento através da propriedade Document.Comments[int].
  • Inicialize uma instância da classe Comment para criar um novo comentário. Em seguida, defina o conteúdo e o autor do comentário.
  • Adicione o novo comentário como resposta ao comentário específico usando o método Comment.ReplyToComment().
  • Salve o documento resultante usando o 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

Excluir comentários no Word em C# e VB.NET

Spire.Doc for .NET oferece o método Document.Comments.RemoveAt(int) para remover um comentário específico de um documento do Word e o método Document.Comments.Clear() para remover todos os comentários de um documento do Word. A seguir estão as etapas detalhadas:

  • Inicialize uma instância da classe Document.
  • Carregue um documento do Word usando o método Document.LoadFromFile().
  • Exclua um comentário específico ou todos os comentários do documento usando o método Document.Comments.RemoveAt(int) ou o método Document.Comments.Clear().
  • Salve o documento resultante usando o 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 uma licença temporária

Se desejar remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, por favor solicite uma licença de teste de 30 dias para você mesmo.

Veja também

Функция комментариев в Microsoft Word предоставляет людям отличный способ добавить свои идеи или мнения в документ Word без необходимости изменять или прерывать содержимое документа. Если кто-то комментирует документ, автор документа или другие пользователи могут ответить на комментарий, чтобы обсудить с ним, даже если они не просматривают документ одновременно. В этой статье будет показано, как добавлять, отвечать на комментарии или удалять комментарии в Word на C# и VB.NET с помощью библиотеки Spire.Doc for .NET.

Установите Spire.Doc for .NET

Для начала вам необходимо добавить файлы DLL, включенные в пакет Spire.Doc for .NET, в качестве ссылок в ваш проект .NET. Файлы DLL можно загрузить по этой ссылке или установить через NuGet.

PM> Install-Package Spire.Doc

Добавление комментария к абзацу в Word на C# и VB.NET

Spire.Doc for .NET предоставляет метод Paragraph.AppendComment() для добавления комментария к определенному абзацу. Ниже приведены подробные шаги:

  • Инициализируйте экземпляр класса Document.
  • Загрузите документ Word с помощью метода Document.LoadFromFile().
  • Доступ к определенному разделу документа по его индексу через свойство Document.Sections[int].
  • Доступ к определенному абзацу раздела по его индексу через свойство Раздел.Параграфы[int].
  • Добавьте комментарий к абзацу, используя метод Paragraph.AppendComment().
  • Установите автора комментария через свойство Comment.Format.Author.
  • Сохраните полученный документ с помощью метода 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

Добавление комментария к тексту в Word на C# и VB.NET

Метод Paragraph.AppendComment() используется для добавления комментариев ко всему абзацу. По умолчанию знаки комментариев будут размещены в конце абзаца. Чтобы добавить комментарий к определенному тексту, вам необходимо выполнить поиск текста с помощью метода Document.FindString(), а затем разместить метки комментариев в начале и конце текста. Ниже приведены подробные шаги:

  • Инициализируйте экземпляр класса Document.
  • Загрузите документ Word с помощью метода Document.LoadFromFile().
  • Найдите определенный текст в документе, используя метод Document.FindString().
  • Создайте метку начала комментария и метку конца комментария, которые будут размещены в начале и конце найденного текста соответственно.
  • Инициализируйте экземпляр класса Comment, чтобы создать новый комментарий. Затем укажите содержание и автора комментария.
  • Получите владелец абзаца найденного текста. Затем добавьте комментарий к абзацу как дочерний объект.
  • Вставьте метку начала комментария перед текстовым диапазоном и метку конца комментария после текстового диапазона.
  • Сохраните полученный документ с помощью метода 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

Ответ на комментарий в Word на C# и VB.NET

Чтобы добавить ответ на существующий комментарий, вы можете использовать метод Comment.ReplyToComment(). Ниже приведены подробные шаги:

  • Инициализируйте экземпляр класса Document.
  • Загрузите документ Word с помощью метода Document.LoadFromFile().
  • Получите конкретный комментарий в документе через свойство Document.Comments[int].
  • Инициализируйте экземпляр класса Comment, чтобы создать новый комментарий. Затем установите содержимое и автора комментария.
  • Добавьте новый комментарий в качестве ответа на конкретный комментарий, используя метод Comment.ReplyToComment().
  • Сохраните полученный документ с помощью метода 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

Удаление комментариев в Word на C# и VB.NET

Spire.Doc for .NET предлагает метод Document.Comments.RemoveAt(int) для удаления определенного комментария из документа Word и метод Document.Comments.Clear() для удаления всех комментариев из документа Word. Ниже приведены подробные шаги:

  • Инициализируйте экземпляр класса Document.
  • Загрузите документ Word с помощью метода Document.LoadFromFile().
  • Удалите определенный комментарий или все комментарии в документе с помощью метода Document.Comments.RemoveAt(int) или Document.Comments.Clear().
  • Сохраните полученный документ с помощью метода 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

Подать заявку на временную лицензию

Если вы хотите удалить сообщение об оценке из сгенерированных документов или избавиться от ограничений функции, пожалуйста запросите 30-дневную пробную лицензию для себя.

Смотрите также

Die Kommentarfunktion in Microsoft Word bietet Benutzern eine hervorragende Möglichkeit, ihre Erkenntnisse oder Meinungen zu einem Word-Dokument hinzuzufügen, ohne den Inhalt des Dokuments ändern oder unterbrechen zu müssen. Wenn jemand ein Dokument kommentiert, können der Autor des Dokuments oder andere Benutzer auf den Kommentar antworten, um mit ihm zu diskutieren, auch wenn sie das Dokument nicht gleichzeitig anzeigen. Dieser Artikel zeigt, wie das geht Hinzufügen, Beantworten oder Löschen von Kommentaren in Word in C# und VB.NET mithilfe der Spire.Doc for .NET-Bibliothek.

Installieren Sie Spire.Doc for .NET

Zunächst müssen Sie die im Spire.Doc for.NET-Paket enthaltenen DLL-Dateien als Referenzen in Ihrem .NET-Projekt hinzufügen. Die DLL-Dateien können entweder über diesen Link heruntergeladen oder über NuGet installiert werden.

PM> Install-Package Spire.Doc

Fügen Sie einen Kommentar zu einem Absatz in Word in C# und VB.NET hinzu

Spire.Doc for .NET bietet die Methode Paragraph.AppendComment(), um einem bestimmten Absatz einen Kommentar hinzuzufügen. Im Folgenden sind die detaillierten Schritte aufgeführt:

  • Initialisieren Sie eine Instanz der Document-Klasse.
  • Laden Sie ein Word-Dokument mit der Methode Document.LoadFromFile().
  • Greifen Sie über die Eigenschaft Document.Sections[int] über seinen Index auf einen bestimmten Abschnitt im Dokument zu.
  • Greifen Sie über die Section.Paragraphs[int]-Eigenschaft auf einen bestimmten Absatz im Abschnitt über seinen Index zu.
  • Fügen Sie mit der Methode Paragraph.AppendComment() einen Kommentar zum Absatz hinzu.
  • Legen Sie den Autor des Kommentars über die Eigenschaft Comment.Format.Author fest.
  • Speichern Sie das Ergebnisdokument mit der Methode 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

Fügen Sie einen Kommentar zu Text in Word in C# und VB.NET hinzu

Die Methode Paragraph.AppendComment() wird verwendet, um Kommentare zu einem gesamten Absatz hinzuzufügen. Standardmäßig werden die Kommentarzeichen am Ende des Absatzes platziert. Um einem bestimmten Text einen Kommentar hinzuzufügen, müssen Sie mit der Methode Document.FindString() nach dem Text suchen und dann die Kommentarmarkierungen am Anfang und Ende des Textes platzieren. Im Folgenden sind die detaillierten Schritte aufgeführt:

  • Initialisieren Sie eine Instanz der Document-Klasse.
  • Laden Sie ein Word-Dokument mit der Methode Document.LoadFromFile().
  • Suchen Sie den spezifischen Text im Dokument mit der Methode Document.FindString().
  • Erstellen Sie eine Kommentar-Startmarkierung und eine Kommentar-Endmarkierung, die jeweils am Anfang und am Ende des gefundenen Textes platziert werden.
  • Initialisieren Sie eine Instanz der Comment-Klasse, um einen neuen Kommentar zu erstellen. Legen Sie dann den Inhalt und den Autor für den Kommentar fest.
  • Holen Sie sich den Eigentümerabsatz des gefundenen Textes. Fügen Sie dann den Kommentar als untergeordnetes Objekt zum Absatz hinzu.
  • Fügen Sie die Kommentar-Startmarkierung vor dem Textbereich und die Kommentar-Endmarkierung nach dem Textbereich ein.
  • Speichern Sie das Ergebnisdokument mit der Methode 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

Antworten Sie auf einen Kommentar in Word in C# und VB.NET

Um eine Antwort auf einen vorhandenen Kommentar hinzuzufügen, können Sie die Methode Comment.ReplyToComment() verwenden. Im Folgenden sind die detaillierten Schritte aufgeführt:

  • Initialisieren Sie eine Instanz der Document-Klasse.
  • Laden Sie ein Word-Dokument mit der Methode Document.LoadFromFile().
  • Rufen Sie über die Eigenschaft Document.Comments[int] einen bestimmten Kommentar im Dokument ab.
  • Initialisieren Sie eine Instanz der Comment-Klasse, um einen neuen Kommentar zu erstellen. Legen Sie dann den Inhalt und den Autor für den Kommentar fest.
  • Fügen Sie den neuen Kommentar als Antwort auf den spezifischen Kommentar hinzu, indem Sie die Methode Comment.ReplyToComment() verwenden.
  • Speichern Sie das Ergebnisdokument mit der Methode 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

Löschen Sie Kommentare in Word in C# und VB.NET

Spire.Doc for .NET bietet die Methode Document.Comments.RemoveAt(int) zum Entfernen eines bestimmten Kommentars aus einem Word-Dokument und die Methode Document.Comments.Clear() zum Entfernen aller Kommentare aus einem Word-Dokument. Im Folgenden sind die detaillierten Schritte aufgeführt:

  • Initialisieren Sie eine Instanz der Document-Klasse.
  • Laden Sie ein Word-Dokument mit der Methode Document.LoadFromFile().
  • Löschen Sie einen bestimmten Kommentar oder alle Kommentare im Dokument mit der Methode Document.Comments.RemoveAt(int) oder der Methode Document.Comments.Clear().
  • Speichern Sie das Ergebnisdokument mit der Methode 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

Beantragen Sie eine temporäre Lizenz

Wenn Sie die Bewertungsmeldung aus den generierten Dokumenten entfernen oder die Funktionseinschränkungen beseitigen möchten, wenden Sie sich bitte an uns Fordern Sie eine 30-Tage-Testlizenz an für sich selbst.

Siehe auch

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

Microsoft Word의 주석 기능은 사람들이 문서의 내용을 변경하거나 중단하지 않고도 Word 문서에 통찰력이나 의견을 추가할 수 있는 훌륭한 방법을 제공합니다. 누군가 문서에 댓글을 달면 문서 작성자나 다른 사용자는 동시에 문서를 보고 있지 않더라도 댓글에 답하여 그 사람과 토론할 수 있습니다. 이 문서에서는 다음 방법을 보여줍니다 C# 및 VB.NET의 Word에서 주석 추가, 회신 또는 삭제 사용하여 Spire.Doc for .NET 도서관.

Spire.Doc for .NET 설치

먼저 Spire.Doc for.NET 패키지에 포함된 DLL 파일을 .NET 프로젝트의 참조로 추가해야 합니다. DLL 파일은 이 링크 에서 다운로드하거나 NuGet을 통해 설치할 수 있습니다.

PM> Install-Package Spire.Doc

C# 및 VB.NET에서 Word의 단락에 설명 추가

Spire.Doc for .NET은 특정 단락에 주석을 추가하기 위한 Paragraph.AppendComment() 메서드를 제공합니다. 자세한 단계는 다음과 같습니다.

  • Document 클래스의 인스턴스를 초기화합니다.
  • Document.LoadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
  • Document.Sections[int] 속성을 통해 해당 인덱스로 문서의 특정 섹션에 액세스합니다.
  • Section.Paragraphs[int] 속성을 통해 해당 색인으로 섹션의 특정 단락에 액세스합니다.
  • Paragraph.AppendComment() 메서드를 사용하여 단락에 설명을 추가합니다.
  • Comment.Format.Author 속성을 통해 댓글 작성자를 설정합니다.
  • 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

C# 및 VB.NET에서 Word의 텍스트에 설명 추가

Paragraph.AppendComment() 메서드는 전체 단락에 주석을 추가하는 데 사용됩니다. 기본적으로 주석 표시는 단락 끝에 배치됩니다. 특정 텍스트에 주석을 추가하려면 Document.FindString() 메서드를 사용하여 텍스트를 검색한 다음 텍스트의 시작과 끝 부분에 주석 표시를 배치해야 합니다. 자세한 단계는 다음과 같습니다.

  • Document 클래스의 인스턴스를 초기화합니다.
  • Document.LoadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
  • Document.FindString() 메서드를 사용하여 문서에서 특정 텍스트를 찾습니다.
  • 찾은 텍스트의 시작과 끝 부분에 각각 배치될 주석 시작 표시와 주석 끝 표시를 만듭니다.
  • 새 댓글을 생성하려면 Comment 클래스의 인스턴스를 초기화하세요. 그런 다음 댓글의 내용과 작성자를 설정합니다.
  • 발견된 텍스트의 소유자 단락을 가져옵니다. 그런 다음 단락에 주석을 하위 개체로 추가합니다.
  • 텍스트 범위 앞에 주석 시작 표시를 삽입하고 텍스트 범위 뒤에 주석 끝 표시를 삽입합니다.
  • 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

C# 및 VB.NET의 Word에서 주석에 응답

기존 댓글에 답글을 추가하려면 Comment.ReplyToComment() 메서드를 사용할 수 있습니다. 자세한 단계는 다음과 같습니다.

  • Document 클래스의 인스턴스를 초기화합니다.
  • Document.LoadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
  • Document.Comments[int] 속성을 통해 문서의 특정 설명을 가져옵니다.
  • 새 댓글을 생성하려면 Comment 클래스의 인스턴스를 초기화하세요. 그런 다음 댓글의 내용과 작성자를 설정합니다.
  • Comment.ReplyToComment() 메서드를 사용하여 특정 댓글에 대한 응답으로 새 댓글을 추가합니다.
  • 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

C# 및 VB.NET의 Word에서 주석 삭제

Spire.Doc for .NET Word 문서에서 특정 주석을 제거하는 Document.Comments.RemoveAt(int) 메서드와 Word 문서에서 모든 주석을 제거하는 Document.Comments.Clear() 메서드를 제공합니다. 자세한 단계는 다음과 같습니다.

  • Document 클래스의 인스턴스를 초기화합니다.
  • Document.LoadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
  • Document.Comments.RemoveAt(int) 메서드 또는 Document.Comments.Clear() 메서드를 사용하여 문서의 특정 주석 또는 모든 주석을 삭제합니다.
  • 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

임시 라이센스 신청

생성된 문서에서 평가 메시지를 제거하고 싶거나, 기능 제한을 없애고 싶다면 30일 평가판 라이센스 요청 자신을 위해.

또한보십시오

La funzionalità di commento in Microsoft Word offre alle persone un modo eccellente per aggiungere i propri approfondimenti o opinioni a un documento di Word senza dover modificare o interrompere il contenuto del documento. Se qualcuno commenta un documento, l'autore del documento o altri utenti possono rispondere al commento per discutere con lui, anche se non stanno visualizzando il documento contemporaneamente. Questo articolo mostrerà come farlo aggiungere, rispondere o eliminare commenti in Word in C# e VB.NET utilizzando la libreria Spire.Doc for .NET.

Installa Spire.Doc for .NET

Per cominciare, devi aggiungere i file DLL inclusi nel pacchetto Spire.Doc per.NET come riferimenti nel tuo progetto .NET. I file DLL possono essere scaricati da questo link o installato tramite NuGet.

PM> Install-Package Spire.Doc

Aggiungi un commento al paragrafo in Word in C# e VB.NET

Spire.Doc for .NET fornisce il metodo Paragraph.AppendComment() per aggiungere un commento a un paragrafo specifico. Di seguito sono riportati i passaggi dettagliati:

  • Inizializza un'istanza della classe Document.
  • Carica un documento Word utilizzando il metodo Document.LoadFromFile().
  • Accedi a una sezione specifica del documento tramite il suo indice tramite la proprietà Document.Sections[int].
  • Accedi a un paragrafo specifico nella sezione tramite il suo indice tramite la proprietà Sezione.Paragraphs[int].
  • Aggiungi un commento al paragrafo utilizzando il metodo Paragraph.AppendComment().
  • Imposta l'autore del commento tramite la proprietà Comment.Format.Author.
  • Salvare il documento risultante utilizzando il metodo 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

Aggiungi un commento al testo in Word in C# e VB.NET

Il metodo Paragraph.AppendComment() viene utilizzato per aggiungere commenti a un intero paragrafo. Per impostazione predefinita, i contrassegni di commento verranno posizionati alla fine del paragrafo. Per aggiungere un commento a un testo specifico, è necessario cercare il testo utilizzando il metodo Document.FindString(), quindi posizionare i contrassegni di commento all'inizio e alla fine del testo. Di seguito sono riportati i passaggi dettagliati:

  • Inizializza un'istanza della classe Document.
  • Carica un documento Word utilizzando il metodo Document.LoadFromFile().
  • Trova il testo specifico nel documento utilizzando il metodo Document.FindString().
  • Crea un segno di inizio commento e un segno di fine commento, che verranno posizionati rispettivamente all'inizio e alla fine del testo trovato.
  • Inizializza un'istanza della classe Comment per creare un nuovo commento. Quindi imposta il contenuto e l'autore del commento.
  • Ottieni il paragrafo proprietario del testo trovato. Quindi aggiungi il commento al paragrafo come oggetto figlio.
  • Inserisci il segno di inizio commento prima dell'intervallo di testo e il segno di fine commento dopo l'intervallo di testo.
  • Salvare il documento risultante utilizzando il metodo 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

Rispondi a un commento in Word in C# e VB.NET

Per aggiungere una risposta a un commento esistente, puoi utilizzare il metodo Comment.ReplyToComment(). Di seguito sono riportati i passaggi dettagliati:

  • Inizializza un'istanza della classe Document.
  • Carica un documento Word utilizzando il metodo Document.LoadFromFile().
  • Ottieni un commento specifico nel documento tramite la proprietà Document.Comments[int].
  • Inizializza un'istanza della classe Comment per creare un nuovo commento. Quindi imposta il contenuto e l'autore del commento.
  • Aggiungi il nuovo commento come risposta al commento specifico utilizzando il metodo Comment.ReplyToComment().
  • Salvare il documento risultante utilizzando il metodo 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

Elimina commenti in Word in C# e VB.NET

Spire.Doc for .NET offre il metodo Document.Comments.RemoveAt(int) per rimuovere un commento specifico da un documento Word e il metodo Document.Comments.Clear() per rimuovere tutti i commenti da un documento Word. Di seguito sono riportati i passaggi dettagliati:

  • Inizializza un'istanza della classe Document.
  • Carica un documento Word utilizzando il metodo Document.LoadFromFile().
  • Elimina un commento specifico o tutti i commenti nel documento utilizzando il metodo Document.Comments.RemoveAt(int) o Document.Comments.Clear().
  • Salvare il documento risultante utilizzando il metodo 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

Richiedi una licenza temporanea

Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni della funzione, per favore richiedere una licenza di prova di 30 giorni per te.

Guarda anche

La fonctionnalité de commentaire de Microsoft Word constitue un excellent moyen permettant aux utilisateurs d'ajouter leurs idées ou leurs opinions à un document Word sans avoir à modifier ou interrompre le contenu du document. Si quelqu'un commente un document, l'auteur du document ou d'autres utilisateurs peuvent répondre au commentaire pour discuter avec lui, même s'ils ne consultent pas le document en même temps. Cet article montrera comment ajoutez, répondez ou supprimez des commentaires dans Word en C# et VB.NET à l'aide de la bibliothèque Spire.Doc for .NET.

Installer Spire.Doc for .NET

Pour commencer, vous devez ajouter les fichiers DLL inclus dans le package Spire.Doc for.NET comme références dans votre projet .NET. Les fichiers DLL peuvent être téléchargés à partir de ce lien ou installés via NuGet.

PM> Install-Package Spire.Doc

Ajouter un commentaire au paragraphe dans Word en C# et VB.NET

Spire.Doc for .NET fournit la méthode Paragraph.AppendComment() pour ajouter un commentaire à un paragraphe spécifique. Voici les étapes détaillées :

  • Initialisez une instance de la classe Document.
  • Chargez un document Word à l'aide de la méthode Document.LoadFromFile().
  • Accédez à une section spécifique du document par son index via la propriété Document.Sections[int].
  • Accédez à un paragraphe spécifique de la section par son index via la propriété Section.Paragraphs[int].
  • Ajoutez un commentaire au paragraphe à l’aide de la méthode Paragraph.AppendComment().
  • Définissez l’auteur du commentaire via la propriété Comment.Format.Author.
  • Enregistrez le document résultat à l'aide de la méthode 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

Ajouter un commentaire au texte dans Word en C# et VB.NET

La méthode Paragraph.AppendComment() est utilisée pour ajouter des commentaires à un paragraphe entier. Par défaut, les marques de commentaire seront placées à la fin du paragraphe. Pour ajouter un commentaire à un texte spécifique, vous devez rechercher le texte à l'aide de la méthode Document.FindString(), puis placer les marques de commentaire au début et à la fin du texte. Voici les étapes détaillées :

  • Initialisez une instance de la classe Document.
  • Chargez un document Word à l'aide de la méthode Document.LoadFromFile().
  • Recherchez le texte spécifique dans le document à l'aide de la méthode Document.FindString().
  • Créez une marque de début de commentaire et une marque de fin de commentaire, qui seront placées respectivement au début et à la fin du texte trouvé.
  • Initialisez une instance de la classe Comment pour créer un nouveau commentaire. Définissez ensuite le contenu et l'auteur du commentaire.
  • Obtenez le paragraphe propriétaire du texte trouvé. Ajoutez ensuite le commentaire au paragraphe en tant qu'objet enfant.
  • Insérez la marque de début du commentaire avant la plage de texte et la marque de fin du commentaire après la plage de texte.
  • Enregistrez le document résultat à l'aide de la méthode 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

Répondre à un commentaire dans Word en C# et VB.NET

Pour ajouter une réponse à un commentaire existant, vous pouvez utiliser la méthode Comment.ReplyToComment(). Voici les étapes détaillées :

  • Initialisez une instance de la classe Document.
  • Chargez un document Word à l'aide de la méthode Document.LoadFromFile().
  • Obtenez un commentaire spécifique dans le document via la propriété Document.Comments[int].
  • Initialisez une instance de la classe Comment pour créer un nouveau commentaire.Définissez ensuite le contenu et l'auteur du commentaire.
  • Ajoutez le nouveau commentaire en réponse au commentaire spécifique à l'aide de la méthode Comment.ReplyToComment().
  • Enregistrez le document résultat à l'aide de la méthode 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

Supprimer des commentaires dans Word en C# et VB.NET

Spire.Doc for .NET propose la méthode Document.Comments.RemoveAt(int) pour supprimer un commentaire spécifique d'un document Word et la méthode Document.Comments.Clear() pour supprimer tous les commentaires d'un document Word. Voici les étapes détaillées :

  • Initialisez une instance de la classe Document.
  • Chargez un document Word à l'aide de la méthode Document.LoadFromFile().
  • Supprimez un commentaire spécifique ou tous les commentaires du document à l'aide de la méthode Document.Comments.RemoveAt(int) ou Document.Comments.Clear().
  • Enregistrez le document résultat à l'aide de la méthode 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

Demander une licence temporaire

Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations fonctionnelles, veuillez demander une licence d'essai de 30 jours pour toi.

Voir également

Wednesday, 27 September 2023 06:22

C#/VB.NET: Insert Hyperlinks to Word Documents

Installed via NuGet

PM> Install-Package Spire.Doc

Related Links

A hyperlink within a Word document enables readers to jump from its location to a different place within the document, or to a different file or website, or to a new email message. Hyperlinks make it quick and easy for readers to navigate to related information. This article demonstrates how to add hyperlinks to text or images in C# and VB.NET using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Insert Hyperlinks When Adding Paragraphs to Word

Spire.Doc offers the Paragraph.AppendHyperlink() method to add a web link, an email link, a file link, or a bookmark link to a piece of text or an image inside a paragraph. The following are the detailed steps.

  • Create a Document object.
  • Add a section and a paragraph to it.
  • Insert a hyperlink based on text using Paragraph.AppendHyerplink(string link, string text, HyperlinkType type) method.
  • Add an image to the paragraph using Paragraph.AppendPicture() method.
  • Insert a hyperlink based on the image using Paragraph.AppendHyerplink(string link, Spire.Doc.Fields.DocPicture picture, HyperlinkType type) method.
  • Save the document using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
    using Spire.Doc.Documents;
    using System.Drawing;
    
    namespace InsertHyperlinks
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Word document
                Document doc = new Document();
    
                //Add a section
                Section section = doc.AddSection();
    
                //Add a paragraph
                Paragraph paragraph = section.AddParagraph();
                paragraph.AppendHyperlink("https://www-iceblue.com/", "Home Page", HyperlinkType.WebLink);
    
                //Append line breaks
                paragraph.AppendBreak(BreakType.LineBreak);
                paragraph.AppendBreak(BreakType.LineBreak);
    
                //Add an email link
                paragraph.AppendHyperlink("mailto:support@e-iceblue.com", "Mail Us", HyperlinkType.EMailLink);
    
                //Append line breaks
                paragraph.AppendBreak(BreakType.LineBreak);
                paragraph.AppendBreak(BreakType.LineBreak);
    
                //Add a file link
                string filePath = @"C:\Users\Administrator\Desktop\report.xlsx";
                paragraph.AppendHyperlink(filePath, "Click to open the report", HyperlinkType.FileLink);
    
                //Append line breaks
                paragraph.AppendBreak(BreakType.LineBreak);
                paragraph.AppendBreak(BreakType.LineBreak);
    
                //Add another section and create a bookmark
                Section section2 = doc.AddSection();
                Paragraph bookmarkParagrapg = section2.AddParagraph();
                bookmarkParagrapg.AppendText("Here is a bookmark");
                BookmarkStart start = bookmarkParagrapg.AppendBookmarkStart("myBookmark");
                bookmarkParagrapg.Items.Insert(0, start);
                bookmarkParagrapg.AppendBookmarkEnd("myBookmark");
    
                //Link to the bookmark
                paragraph.AppendHyperlink("myBookmark", "Jump to a location inside this document", HyperlinkType.Bookmark);
    
                //Append line breaks
                paragraph.AppendBreak(BreakType.LineBreak);
                paragraph.AppendBreak(BreakType.LineBreak);
    
                //Add an image link
                Image image = Image.FromFile(@"C:\Users\Administrator\Desktop\logo.png");
                Spire.Doc.Fields.DocPicture picture = paragraph.AppendPicture(image);
                paragraph.AppendHyperlink("https://docs.microsoft.com/en-us/dotnet/", picture, HyperlinkType.WebLink);
    
                //Save to file
                doc.SaveToFile("InsertHyperlinks.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Insert Hyperlinks to Word Documents

Add Hyperlinks to Existing Text in Word

Adding hyperlinks to existing text in a document is a bit more complicated. You’ll need to find the target string first, and then replace it in the paragraph with a hyperlink field. The following are the steps.

  • Create a Document object.
  • Load a Word file using Document.LoadFromFile() method.
  • Find all the occurrences of the target string in the document using Document.FindAllString() method, and get the specific one by its index from the collection.
  • Get the string’s own paragraph and its position in it.
  • Remove the string from the paragraph.
  • Create a hyperlink field and insert it to position where the string is located.
  • Save the document to another file using Document.SaveToFle() method.
  • C#
  • VB.NET
using Spire.Doc;
    using Spire.Doc.Documents;
    using Spire.Doc.Fields;
    using Spire.Doc.Interface;
    
    namespace AddHyperlinksToExistingText
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document document = new Document();
    
                //Load a Word file
                document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx");
    
                //Find all the occurrences of the string ".NET Framework" in the document
                TextSelection[] selections = document.FindAllString(".NET Framework", true, true);
    
                //Get the second occurrence
                TextRange range = selections[1].GetAsOneRange();
    
                //Get its owner paragraph
                Paragraph parapgraph = range.OwnerParagraph;
    
                //Get its position in the paragraph
                int index = parapgraph.Items.IndexOf(range);
    
                //Remove it from the paragraph
                parapgraph.Items.Remove(range);
    
                //Create a hyperlink field
                Spire.Doc.Fields.Field field = new Spire.Doc.Fields.Field(document);
                field.Type = Spire.Doc.FieldType.FieldHyperlink;
                Hyperlink hyperlink = new Hyperlink(field);
                hyperlink.Type = HyperlinkType.WebLink;
                hyperlink.Uri = "https://en.wikipedia.org/wiki/.NET_Framework";
                parapgraph.Items.Insert(index, field);
    
                //Insert a field mark "start" to the paragraph
                IParagraphBase start = document.CreateParagraphItem(ParagraphItemType.FieldMark);
                (start as FieldMark).Type = FieldMarkType.FieldSeparator;
                parapgraph.Items.Insert(index + 1, start);
    
                //Insert a text range between two field marks
                ITextRange textRange = new Spire.Doc.Fields.TextRange(document);
                textRange.Text = ".NET Framework";
                textRange.CharacterFormat.Font = range.CharacterFormat.Font;
                textRange.CharacterFormat.TextColor = System.Drawing.Color.Blue;
                textRange.CharacterFormat.UnderlineStyle = UnderlineStyle.Single;
                parapgraph.Items.Insert(index + 2, textRange);
    
                //Insert a field mark "end" to the paragraph
                IParagraphBase end = document.CreateParagraphItem(ParagraphItemType.FieldMark);
                (end as FieldMark).Type = FieldMarkType.FieldEnd;
                parapgraph.Items.Insert(index + 3, end);
    
                //Save to file
                document.SaveToFile("AddHyperlink.docx", Spire.Doc.FileFormat.Docx);
            }
        }
    }

C#/VB.NET: Insert Hyperlinks to Word Documents

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

See Also

Um hiperlink em um documento do Word permite que os leitores saltem de seu local para um local diferente no documento, ou para um arquivo ou site diferente, ou para uma nova mensagem de email. Os hiperlinks facilitam e agilizam a navegação dos leitores pelas informações relacionadas. Este artigo demonstra como adicionar hiperlinks a texto ou imagens em C# e VB.NET usando Spire.Doc for .NET.

Instale o Spire.Doc for .NET

Para começar, você precisa adicionar os arquivos DLL incluídos no pacote Spire.Doc for.NET como referências em seu projeto .NET. Os arquivos DLL podem ser baixados deste link ou instalados via NuGet.

PM> Install-Package Spire.Doc

Insira hiperlinks ao adicionar parágrafos ao Word

Spire.Doc oferece o método Paragraph.AppendHyperlink() para adicionar um link da web, um link de e-mail, um link de arquivo ou um link de marcador a um trecho de texto ou imagem dentro de um parágrafo. A seguir estão as etapas detalhadas.

  • Crie um objeto Documento.
  • Adicione uma seção e um parágrafo a ela.
  • Insira um hiperlink baseado em texto usando o método Paragraph.AppendHyerplink(string link, string text, HyperlinkType type).
  • Adicione uma imagem ao parágrafo usando o método Paragraph.AppendPicture().
  • Insira um hiperlink baseado na imagem usando o método Paragraph.AppendHyerplink (string link, Spire.Doc.Fields.DocPicture picture, HyperlinkType type).
  • Salve o documento usando o método Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    using Spire.Doc.Documents;
    using System.Drawing;
    
    namespace InsertHyperlinks
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Word document
                Document doc = new Document();
    
                //Add a section
                Section section = doc.AddSection();
    
                //Add a paragraph
                Paragraph paragraph = section.AddParagraph();
                paragraph.AppendHyperlink("https://www-iceblue.com/", "Home Page", HyperlinkType.WebLink);
    
                //Append line breaks
                paragraph.AppendBreak(BreakType.LineBreak);
                paragraph.AppendBreak(BreakType.LineBreak);
    
                //Add an email link
                paragraph.AppendHyperlink("mailto:support@e-iceblue.com", "Mail Us", HyperlinkType.EMailLink);
    
                //Append line breaks
                paragraph.AppendBreak(BreakType.LineBreak);
                paragraph.AppendBreak(BreakType.LineBreak);
    
                //Add a file link
                string filePath = @"C:\Users\Administrator\Desktop\report.xlsx";
                paragraph.AppendHyperlink(filePath, "Click to open the report", HyperlinkType.FileLink);
    
                //Append line breaks
                paragraph.AppendBreak(BreakType.LineBreak);
                paragraph.AppendBreak(BreakType.LineBreak);
    
                //Add another section and create a bookmark
                Section section2 = doc.AddSection();
                Paragraph bookmarkParagrapg = section2.AddParagraph();
                bookmarkParagrapg.AppendText("Here is a bookmark");
                BookmarkStart start = bookmarkParagrapg.AppendBookmarkStart("myBookmark");
                bookmarkParagrapg.Items.Insert(0, start);
                bookmarkParagrapg.AppendBookmarkEnd("myBookmark");
    
                //Link to the bookmark
                paragraph.AppendHyperlink("myBookmark", "Jump to a location inside this document", HyperlinkType.Bookmark);
    
                //Append line breaks
                paragraph.AppendBreak(BreakType.LineBreak);
                paragraph.AppendBreak(BreakType.LineBreak);
    
                //Add an image link
                Image image = Image.FromFile(@"C:\Users\Administrator\Desktop\logo.png");
                Spire.Doc.Fields.DocPicture picture = paragraph.AppendPicture(image);
                paragraph.AppendHyperlink("https://docs.microsoft.com/en-us/dotnet/", picture, HyperlinkType.WebLink);
    
                //Save to file
                doc.SaveToFile("InsertHyperlinks.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Insert Hyperlinks to Word Documents

Adicionar hiperlinks a texto existente no Word

Adicionar hiperlinks ao texto existente em um documento é um pouco mais complicado. Você precisará primeiro encontrar a string de destino e, em seguida, substituí-la no parágrafo por um campo de hiperlink. A seguir estão as etapas.

  • Crie um objeto Documento.
  • Carregue um arquivo Word usando o método Document.LoadFromFile().
  • Encontre todas as ocorrências da string de destino no documento usando o método Document.FindAllString() e obtenha aquela específica por seu índice da coleção.
  • Obtenha o próprio parágrafo da string e sua posição nele.
  • Remova a string do parágrafo.
  • Crie um campo de hiperlink e insira-o na posição onde a string está localizada.
  • Salve o documento em outro arquivo usando o método Document.SaveToFle().
  • C#
  • VB.NET
using Spire.Doc;
    using Spire.Doc.Documents;
    using Spire.Doc.Fields;
    using Spire.Doc.Interface;
    
    namespace AddHyperlinksToExistingText
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document document = new Document();
    
                //Load a Word file
                document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx");
    
                //Find all the occurrences of the string ".NET Framework" in the document
                TextSelection[] selections = document.FindAllString(".NET Framework", true, true);
    
                //Get the second occurrence
                TextRange range = selections[1].GetAsOneRange();
    
                //Get its owner paragraph
                Paragraph parapgraph = range.OwnerParagraph;
    
                //Get its position in the paragraph
                int index = parapgraph.Items.IndexOf(range);
    
                //Remove it from the paragraph
                parapgraph.Items.Remove(range);
    
                //Create a hyperlink field
                Spire.Doc.Fields.Field field = new Spire.Doc.Fields.Field(document);
                field.Type = Spire.Doc.FieldType.FieldHyperlink;
                Hyperlink hyperlink = new Hyperlink(field);
                hyperlink.Type = HyperlinkType.WebLink;
                hyperlink.Uri = "https://en.wikipedia.org/wiki/.NET_Framework";
                parapgraph.Items.Insert(index, field);
    
                //Insert a field mark "start" to the paragraph
                IParagraphBase start = document.CreateParagraphItem(ParagraphItemType.FieldMark);
                (start as FieldMark).Type = FieldMarkType.FieldSeparator;
                parapgraph.Items.Insert(index + 1, start);
    
                //Insert a text range between two field marks
                ITextRange textRange = new Spire.Doc.Fields.TextRange(document);
                textRange.Text = ".NET Framework";
                textRange.CharacterFormat.Font = range.CharacterFormat.Font;
                textRange.CharacterFormat.TextColor = System.Drawing.Color.Blue;
                textRange.CharacterFormat.UnderlineStyle = UnderlineStyle.Single;
                parapgraph.Items.Insert(index + 2, textRange);
    
                //Insert a field mark "end" to the paragraph
                IParagraphBase end = document.CreateParagraphItem(ParagraphItemType.FieldMark);
                (end as FieldMark).Type = FieldMarkType.FieldEnd;
                parapgraph.Items.Insert(index + 3, end);
    
                //Save to file
                document.SaveToFile("AddHyperlink.docx", Spire.Doc.FileFormat.Docx);
            }
        }
    }

C#/VB.NET: Insert Hyperlinks to Word Documents

Solicite uma licença temporária

Se desejar remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, por favor solicite uma licença de teste de 30 dias para você mesmo.

Veja também

Гиперссылка в документе Word позволяет читателям перейти из ее местоположения в другое место документа, к другому файлу или веб-сайту, или к новому сообщению электронной почты. Гиперссылки позволяют читателям быстро и легко перейти к соответствующей информации. В этой статье показано, как добавляйте гиперссылки на текст или изображения в C# и VB.NET с помощью Spire.Doc for .NET.

Установите Spire.Doc for .NET

Для начала вам необходимо добавить файлы DLL, включенные в пакет Spire.Doc for .NET, в качестве ссылок в ваш проект .NET. Файлы DLL можно загрузить по этой ссылке или установить через NuGet.

PM> Install-Package Spire.Doc

Вставка гиперссылок при добавлении абзацев в Word

Spire.Doc предлагает метод Paragraph.AppendHyperlink() для добавления веб-ссылки, ссылки по электронной почте, ссылки на файл или ссылки на закладку к фрагменту текста или изображению внутри абзаца. Ниже приведены подробные шаги.

  • Создайте объект Документ.
  • Добавьте к нему раздел и абзац.
  • Вставьте гиперссылку на основе текста, используя метод Paragraph.AppendHyerplink(строковая ссылка, текст строки, тип HyperlinkType).
  • Добавьте изображение в абзац, используя метод Paragraph.AppendPicture().
  • Вставьте гиперссылку на основе изображения с помощью метода Paragraph.AppendHyerplink(string link, Spire.Doc.Fields.DocPicture image, тип HyperlinkType).
  • Сохраните документ, используя метод Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    using Spire.Doc.Documents;
    using System.Drawing;
    
    namespace InsertHyperlinks
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Word document
                Document doc = new Document();
    
                //Add a section
                Section section = doc.AddSection();
    
                //Add a paragraph
                Paragraph paragraph = section.AddParagraph();
                paragraph.AppendHyperlink("https://www-iceblue.com/", "Home Page", HyperlinkType.WebLink);
    
                //Append line breaks
                paragraph.AppendBreak(BreakType.LineBreak);
                paragraph.AppendBreak(BreakType.LineBreak);
    
                //Add an email link
                paragraph.AppendHyperlink("mailto:support@e-iceblue.com", "Mail Us", HyperlinkType.EMailLink);
    
                //Append line breaks
                paragraph.AppendBreak(BreakType.LineBreak);
                paragraph.AppendBreak(BreakType.LineBreak);
    
                //Add a file link
                string filePath = @"C:\Users\Administrator\Desktop\report.xlsx";
                paragraph.AppendHyperlink(filePath, "Click to open the report", HyperlinkType.FileLink);
    
                //Append line breaks
                paragraph.AppendBreak(BreakType.LineBreak);
                paragraph.AppendBreak(BreakType.LineBreak);
    
                //Add another section and create a bookmark
                Section section2 = doc.AddSection();
                Paragraph bookmarkParagrapg = section2.AddParagraph();
                bookmarkParagrapg.AppendText("Here is a bookmark");
                BookmarkStart start = bookmarkParagrapg.AppendBookmarkStart("myBookmark");
                bookmarkParagrapg.Items.Insert(0, start);
                bookmarkParagrapg.AppendBookmarkEnd("myBookmark");
    
                //Link to the bookmark
                paragraph.AppendHyperlink("myBookmark", "Jump to a location inside this document", HyperlinkType.Bookmark);
    
                //Append line breaks
                paragraph.AppendBreak(BreakType.LineBreak);
                paragraph.AppendBreak(BreakType.LineBreak);
    
                //Add an image link
                Image image = Image.FromFile(@"C:\Users\Administrator\Desktop\logo.png");
                Spire.Doc.Fields.DocPicture picture = paragraph.AppendPicture(image);
                paragraph.AppendHyperlink("https://docs.microsoft.com/en-us/dotnet/", picture, HyperlinkType.WebLink);
    
                //Save to file
                doc.SaveToFile("InsertHyperlinks.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Insert Hyperlinks to Word Documents

Добавить гиперссылки к существующему тексту в Word

Добавление гиперссылок к существующему тексту в документе немного сложнее. Сначала вам нужно будет найти целевую строку, а затем заменить ее в абзаце полем гиперссылки. Ниже приведены шаги.

  • Создайте объект Документ.
  • Загрузите файл Word с помощью метода Document.LoadFromFile().
  • Найдите все вхождения целевой строки в документе с помощью метода Document.FindAllString() и получите конкретную строку по ее индексу из коллекции.
  • Получите собственный абзац строки и его позицию в нем.
  • Удалите строку из абзаца.
  • Создайте поле гиперссылки и вставьте его в то место, где находится строка.
  • Сохраните документ в другой файл, используя метод Document.SaveToFle().
  • C#
  • VB.NET
using Spire.Doc;
    using Spire.Doc.Documents;
    using Spire.Doc.Fields;
    using Spire.Doc.Interface;
    
    namespace AddHyperlinksToExistingText
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document document = new Document();
    
                //Load a Word file
                document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx");
    
                //Find all the occurrences of the string ".NET Framework" in the document
                TextSelection[] selections = document.FindAllString(".NET Framework", true, true);
    
                //Get the second occurrence
                TextRange range = selections[1].GetAsOneRange();
    
                //Get its owner paragraph
                Paragraph parapgraph = range.OwnerParagraph;
    
                //Get its position in the paragraph
                int index = parapgraph.Items.IndexOf(range);
    
                //Remove it from the paragraph
                parapgraph.Items.Remove(range);
    
                //Create a hyperlink field
                Spire.Doc.Fields.Field field = new Spire.Doc.Fields.Field(document);
                field.Type = Spire.Doc.FieldType.FieldHyperlink;
                Hyperlink hyperlink = new Hyperlink(field);
                hyperlink.Type = HyperlinkType.WebLink;
                hyperlink.Uri = "https://en.wikipedia.org/wiki/.NET_Framework";
                parapgraph.Items.Insert(index, field);
    
                //Insert a field mark "start" to the paragraph
                IParagraphBase start = document.CreateParagraphItem(ParagraphItemType.FieldMark);
                (start as FieldMark).Type = FieldMarkType.FieldSeparator;
                parapgraph.Items.Insert(index + 1, start);
    
                //Insert a text range between two field marks
                ITextRange textRange = new Spire.Doc.Fields.TextRange(document);
                textRange.Text = ".NET Framework";
                textRange.CharacterFormat.Font = range.CharacterFormat.Font;
                textRange.CharacterFormat.TextColor = System.Drawing.Color.Blue;
                textRange.CharacterFormat.UnderlineStyle = UnderlineStyle.Single;
                parapgraph.Items.Insert(index + 2, textRange);
    
                //Insert a field mark "end" to the paragraph
                IParagraphBase end = document.CreateParagraphItem(ParagraphItemType.FieldMark);
                (end as FieldMark).Type = FieldMarkType.FieldEnd;
                parapgraph.Items.Insert(index + 3, end);
    
                //Save to file
                document.SaveToFile("AddHyperlink.docx", Spire.Doc.FileFormat.Docx);
            }
        }
    }

C#/VB.NET: Insert Hyperlinks to Word Documents

Подать заявку на временную лицензию

Если вы хотите удалить сообщение об оценке из сгенерированных документов или избавиться от ограничений функции, пожалуйста запросите 30-дневную пробную лицензию для себя.

Смотрите также