Wednesday, 27 September 2023 06:08

C#/VB.NET: Word에 이미지 삽입

Word 문서의 이미지는 텍스트 내용과 밀접한 관련이 있는 경우가 많습니다. 텍스트로 가득한 문서에 비해 이미지가 포함된 문서는 더 설명적이고 매력적입니다. 이 기사에서는 프로그래밍 방식으로 방법을 배웁니다 Word 문서에 이미지 삽입 Spire.Doc for .NET사용합니다. 이 전문적인 Word 라이브러리를 사용하면 다음과 같은 작업도 할 수 있습니다 이미지 크기, 위치, 배치 스타일을 설정합니다.

Spire.Doc for .NET 설치

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

PM> Install-Package Spire.Doc

Word 문서에 이미지 삽입 및 배치 스타일 설정

Spire.Doc for .NET In Line with Text, Square, Tight, Through, Top and Bottom, Behind the Text 및 In Front of Text와 같은 일반적인 래핑 스타일을 지원합니다. 다음은 이미지를 삽입하고 배치 스타일을 설정하는 자세한 단계입니다.

  • 문서 인스턴스를 만듭니다.
  • Document.LoadFromFile() 메서드를 사용하여 샘플 Word 문서를 로드합니다.
  • Document.Sections[] 속성을 사용하여 Word 문서의 첫 번째 섹션을 가져옵니다.
  • Section.Paragraphs[] 속성을 사용하여 섹션의 지정된 단락을 가져옵니다.
  • Paragraph.AppendPicture() 메서드를 사용하여 이미지를 로드하고 지정된 단락에 이미지를 삽입합니다.
  • DocPicture.TextWrappingType 속성을 사용하여 이미지의 래핑 스타일을 설정합니다.
  • Document.SaveToFile() 메서드를 사용하여 문서를 다른 파일에 저장합니다.
  • C#
  • VB.NET
using System.Drawing;
    using Spire.Doc;
    using Spire.Doc.Documents;
    using Spire.Doc.Fields;
    
    namespace WordImage
    {
        class ImageinWord
        {
            static void Main(string[] args)
            {
                //Create a Document instance
                Document document = new Document();
    
                //Load a sample Word document
                document.LoadFromFile("input.docx");
    
                //Get the first section
                Section section = document.Sections[0];
    
                //Get two specified paragraphs
                Paragraph para1 = section.Paragraphs[5];
                Paragraph para2 = section.Paragraphs[9];
    
                //Insert images in the specified paragraphs
                DocPicture Pic1 = para1.AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic1.jpg"));
                DocPicture Pic2 = para2.AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic2.png"));
    
                //Set wrapping styles to Square and Inline respectively
                Pic1.TextWrappingStyle = TextWrappingStyle.Square;
                Pic2.TextWrappingStyle = TextWrappingStyle.Inline;
    
                //Save the document to file
                document.SaveToFile("InsertImage.docx", FileFormat.Docx);
            }
        }
    }

C#/VB.NET: Insert Images in Word

Word 문서의 지정된 위치에 이미지 삽입

Spire.Doc for .NET에서 제공하는 DocPicture.HorizontalPositionDocPicture.VerticalPosition 속성을 사용하면 지정된 위치에 이미지를 삽입할 수 있습니다. 자세한 단계는 다음과 같습니다.

  • 문서 인스턴스를 만듭니다.
  • Document.LoadFromFile() 메서드를 사용하여 샘플 Word 문서를 로드합니다.
  • Document.Sections[] 속성을 사용하여 Word 문서의 첫 번째 섹션을 가져옵니다.
  • Section.Paragraphs[] 속성을 사용하여 섹션의 지정된 단락을 가져옵니다.
  • Paragraph.AppendPicture() 메서드를 사용하여 이미지를 로드하고 문서에 이미지를 삽입합니다.
  • DocPicture.HorizontalPositionDocPicture.VerticalPosition 속성을 사용하여 이미지의 가로 및 세로 위치를 설정합니다.
  • DocPicture.WidthDocPicture.Height 속성을 사용하여 이미지의 높이와 너비를 설정합니다.
  • DocPicture.TextWrappingType 속성을 사용하여 이미지의 래핑 스타일을 설정합니다.
  • Document.SaveToFile() 메서드를 사용하여 문서를 다른 파일에 저장합니다.
  • C#
  • VB.NET
using Spire.Doc;
    using Spire.Doc.Documents;
    using Spire.Doc.Fields;
    using System.Drawing;
    
    namespace InsertImage
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document instance
                Document document = new Document();
    
                //Load a sample Word document
                document.LoadFromFile("input.docx");
    
                //Get the first section
                Section section = document.Sections[0];
    
                //Load an image and insert it to the document
                DocPicture picture = section.Paragraphs[0].AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic.jpg"));
    
                //Set the position of the image
                picture.HorizontalPosition = 90.0F;
                picture.VerticalPosition = 50.0F;
    
                //Set the size of the image
                picture.Width = 150;
                picture.Height = 150;
    
                //Set the wrapping style to Behind
                picture.TextWrappingStyle = TextWrappingStyle.Behind;
    
                // Save the document to file
                document.SaveToFile("Insert.docx", FileFormat.Docx);
            }
        }
    }

C#/VB.NET: Insert Images in Word

임시 라이센스 신청

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

또한보십시오

Wednesday, 27 September 2023 06:07

C#/VB.NET: inserisci immagini in Word

Le immagini nei documenti Word sono spesso strettamente correlate al contenuto testuale. Rispetto ai documenti pieni di testo, i documenti con immagini sono più illustrativi e attraenti. In questo articolo imparerai come farlo a livello di codice inserire immagini in un documento Word utilizzando Spire.Doc for .NET. Con questa libreria Word professionale, puoi anche farlo imposta la dimensione dell'immagine, la posizione e gli stili di avvolgimento.

Installa Spire.Doc for .NET

Per cominciare, devi aggiungere i file DLL inclusi nel pacchetto Spire.Doc for .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

Inserisci immagini e imposta i relativi stili di disposizione in un documento Word

Spire.Doc for .NET supporta stili di disposizione comuni come In linea con il testo, Quadrato, Stretto, Attraverso, Alto e basso, Dietro il testo e Davanti al testo. Di seguito sono riportati i passaggi dettagliati per inserire immagini e quindi impostare i relativi stili di avvolgimento.

  • Crea un'istanza del documento.
  • Carica un documento Word di esempio utilizzando il metodo Document.LoadFromFile().
  • Ottieni la prima sezione del documento di Word utilizzando la proprietà Document.Sections[].
  • Ottieni un paragrafo specificato della sezione utilizzando la proprietà Sezione.Paragraphs[].
  • Carica un'immagine e inserisci l'immagine nel paragrafo specificato utilizzando il metodo Paragraph.AppendPicture().
  • Imposta lo stile di disposizione dell'immagine utilizzando la proprietà DocPicture.TextWrappingType.
  • Salva il documento in un altro file utilizzando il metodo Document.SaveToFile().
  • C#
  • VB.NET
using System.Drawing;
    using Spire.Doc;
    using Spire.Doc.Documents;
    using Spire.Doc.Fields;
    
    namespace WordImage
    {
        class ImageinWord
        {
            static void Main(string[] args)
            {
                //Create a Document instance
                Document document = new Document();
    
                //Load a sample Word document
                document.LoadFromFile("input.docx");
    
                //Get the first section
                Section section = document.Sections[0];
    
                //Get two specified paragraphs
                Paragraph para1 = section.Paragraphs[5];
                Paragraph para2 = section.Paragraphs[9];
    
                //Insert images in the specified paragraphs
                DocPicture Pic1 = para1.AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic1.jpg"));
                DocPicture Pic2 = para2.AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic2.png"));
    
                //Set wrapping styles to Square and Inline respectively
                Pic1.TextWrappingStyle = TextWrappingStyle.Square;
                Pic2.TextWrappingStyle = TextWrappingStyle.Inline;
    
                //Save the document to file
                document.SaveToFile("InsertImage.docx", FileFormat.Docx);
            }
        }
    }

C#/VB.NET: Insert Images in Word

Inserisci un'immagine in una posizione specificata in un documento di Word

Le proprietà DocPicture.HorizontalPosition e DocPicture.VerticalPosition offerte da Spire.Doc for .NET consentono di inserire un'immagine in una posizione specificata. I passaggi dettagliati sono i seguenti.

  • Crea un'istanza del documento.
  • Carica un documento Word di esempio utilizzando il metodo Document.LoadFromFile().
  • Ottieni la prima sezione del documento di Word utilizzando la proprietà Document.Sections[].
  • Ottieni un paragrafo specificato della sezione utilizzando la proprietà Sezione.Paragraphs[].
  • Carica un'immagine e inserisci l'immagine nel documento utilizzando il metodo Paragraph.AppendPicture().
  • Imposta la posizione orizzontale e verticale dell'immagine utilizzando le proprietà DocPicture.HorizontalPosition e DocPicture.VerticalPosition.
  • Imposta l'altezza e la larghezza dell'immagine utilizzando le proprietà DocPicture.Width e DocPicture.Height.
  • Imposta lo stile di disposizione dell'immagine utilizzando la proprietà DocPicture.TextWrappingType.
  • Salva il documento in un altro file utilizzando il metodo Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    using Spire.Doc.Documents;
    using Spire.Doc.Fields;
    using System.Drawing;
    
    namespace InsertImage
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document instance
                Document document = new Document();
    
                //Load a sample Word document
                document.LoadFromFile("input.docx");
    
                //Get the first section
                Section section = document.Sections[0];
    
                //Load an image and insert it to the document
                DocPicture picture = section.Paragraphs[0].AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic.jpg"));
    
                //Set the position of the image
                picture.HorizontalPosition = 90.0F;
                picture.VerticalPosition = 50.0F;
    
                //Set the size of the image
                picture.Width = 150;
                picture.Height = 150;
    
                //Set the wrapping style to Behind
                picture.TextWrappingStyle = TextWrappingStyle.Behind;
    
                // Save the document to file
                document.SaveToFile("Insert.docx", FileFormat.Docx);
            }
        }
    }

C#/VB.NET: Insert Images 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

Wednesday, 27 September 2023 06:06

C#/VB.NET : insérer des images dans Word

Les images des documents Word sont souvent étroitement liées au contenu textuel. Comparés aux documents remplis de texte, les documents contenant des images sont plus illustratifs et plus attrayants. Dans cet article, vous apprendrez à programmer insérez des images dans un document Word à l'aide de Spire.Doc for .NET. Avec cette bibliothèque Word professionnelle, vous pouvez également définir la taille, la position et les styles d'habillage de l'image.

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

Insérer des images et définir leurs styles d'habillage dans un document Word

Spire.Doc for .NET prend en charge les styles d'habillage courants tels que Aligné avec le texte, Carré, Serré, Traversant, Haut et Bas, Derrière le texte ainsi que Devant le texte. Vous trouverez ci-dessous les étapes détaillées pour insérer des images, puis définir leurs styles d'habillage.

  • Créez une instance de document.
  • Chargez un exemple de document Word à l’aide de la méthode Document.LoadFromFile().
  • Obtenez la première section du document Word à l’aide de la propriété Document.Sections[].
  • Obtenez un paragraphe spécifié de la section à l’aide de la propriété Section.Paragraphs[].
  • Chargez une image et insérez l'image dans le paragraphe spécifié à l'aide de la méthode Paragraph.AppendPicture().
  • Définissez le style d'habillage de l'image à l'aide de la propriété DocPicture.TextWrappingType.
  • Enregistrez le document dans un autre fichier à l'aide de la méthode Document.SaveToFile().
  • C#
  • VB.NET
using System.Drawing;
    using Spire.Doc;
    using Spire.Doc.Documents;
    using Spire.Doc.Fields;
    
    namespace WordImage
    {
        class ImageinWord
        {
            static void Main(string[] args)
            {
                //Create a Document instance
                Document document = new Document();
    
                //Load a sample Word document
                document.LoadFromFile("input.docx");
    
                //Get the first section
                Section section = document.Sections[0];
    
                //Get two specified paragraphs
                Paragraph para1 = section.Paragraphs[5];
                Paragraph para2 = section.Paragraphs[9];
    
                //Insert images in the specified paragraphs
                DocPicture Pic1 = para1.AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic1.jpg"));
                DocPicture Pic2 = para2.AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic2.png"));
    
                //Set wrapping styles to Square and Inline respectively
                Pic1.TextWrappingStyle = TextWrappingStyle.Square;
                Pic2.TextWrappingStyle = TextWrappingStyle.Inline;
    
                //Save the document to file
                document.SaveToFile("InsertImage.docx", FileFormat.Docx);
            }
        }
    }

C#/VB.NET: Insert Images in Word

Insérer une image à un emplacement spécifié dans un document Word

Les propriétés DocPicture.HorizontalPosition et DocPicture.VerticalPosition proposées par Spire.Doc for .NET vous permettent d'insérer une image à un emplacement spécifié. Les étapes détaillées sont les suivantes.

  • Créez une instance de document.
  • Chargez un exemple de document Word à l’aide de la méthode Document.LoadFromFile().
  • Obtenez la première section du document Word à l’aide de la propriété Document.Sections[].
  • Obtenez un paragraphe spécifié de la section à l’aide de la propriété Section.Paragraphs[].
  • Chargez une image et insérez l'image dans le document à l'aide de la méthode Paragraph.AppendPicture().
  • Définissez la position horizontale et verticale de l'image à l'aide des propriétés DocPicture.HorizontalPosition et DocPicture.VerticalPosition.
  • Définissez la hauteur et la largeur de l'image à l'aide des propriétés DocPicture.Width et DocPicture.Height.
  • Définissez le style d'habillage de l'image à l'aide de la propriété DocPicture.TextWrappingType.
  • Enregistrez le document dans un autre fichier à l'aide de la méthode Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    using Spire.Doc.Documents;
    using Spire.Doc.Fields;
    using System.Drawing;
    
    namespace InsertImage
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document instance
                Document document = new Document();
    
                //Load a sample Word document
                document.LoadFromFile("input.docx");
    
                //Get the first section
                Section section = document.Sections[0];
    
                //Load an image and insert it to the document
                DocPicture picture = section.Paragraphs[0].AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\pic.jpg"));
    
                //Set the position of the image
                picture.HorizontalPosition = 90.0F;
                picture.VerticalPosition = 50.0F;
    
                //Set the size of the image
                picture.Width = 150;
                picture.Height = 150;
    
                //Set the wrapping style to Behind
                picture.TextWrappingStyle = TextWrappingStyle.Behind;
    
                // Save the document to file
                document.SaveToFile("Insert.docx", FileFormat.Docx);
            }
        }
    }

C#/VB.NET: Insert Images 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 05:57

C#/VB.NET: Remove Paragraphs in a Word Document

Installed via NuGet

PM> Install-Package Spire.Doc

Related Links

When processing a Word document, you may need to remove some paragraphs. For example, after you copied contents from the Internet with a lot of redundant paragraphs to your document, you need to delete the extra paragraphs and keep only those that are useful. The deletion can be easily achieved by Spire.Doc for .NET by programming with no need for other software. This article will show you the detailed steps of removing paragraphs in a Word document 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

Delete a Specific Paragraph in a Word Document

Spire.Doc for .NET provides a method RemoveAt() under ParagraphCollection to remove paragraphs.

The detailed steps of removing a specific paragraph are as follows:

  • Create an object of Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Get the first section using Document.Section[] property.
  • Remove the 4th paragraph using Section.Paragraphs.RemoveAt() method.
  • Save the document using Document.SaveToFile() method.
  • C#
  • VB.NET
using System;
    using Spire.Doc;
    
    namespace RemoveParagraphs
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Create an object of Document class
                Document document = new Document();
    
                //Load a Word document
                document.LoadFromFile("Sample.docx");
    
                //Get the first section
                Section section = document.Sections[0];
    
                //Remove the first paragraph in the section
                section.Paragraphs.RemoveAt(3);
    
                //Save the document
                document.SaveToFile("RemoveParagraphs.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Remove Paragraphs in a Word Document

Delete All Paragraphs in a Word Document

To remove all paragraphs, you can use the method Clear() under ParagraphCollection provided by Spire.Doc for .NET.

The detailed steps are as follows:

  • Create an object of Document class.
  • Load a Word Document using Document.LoadFromFile() method.
  • Loop through all sections, and remove all paragraphs in each section using Section.Paragraphs.Clear() method.
  • Save the document using Document.SaveToFile() method.
  • C#
  • VB.NET
using System;
    using Spire.Doc;
    
    namespace RemoveAllParagraphs
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Create an object of Document class
                Document document = new Document();
    
                //Load a Word document
                document.LoadFromFile("Sample.docx");
    
                //Loop through all sections
                foreach (Section section in document.Sections)
                {
                    //Remove all paragraphs in the section
                    section.Paragraphs.Clear();
                }
    
                //Save the document
                document.SaveToFile("RemoveAllParagraphs.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Remove Paragraphs in a Word Document

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

Ao processar um documento do Word, pode ser necessário remover alguns parágrafos. Por exemplo, depois de copiar conteúdo da Internet com muitos parágrafos redundantes para o seu documento, você precisa excluir os parágrafos extras e manter apenas aqueles que são úteis. A exclusão pode ser facilmente realizada pelo Spire.Doc for .NET programando sem a necessidade de outro software. Este artigo mostrará as etapas detalhadas de removendo parágrafos em um documento do Word 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

Excluir um parágrafo específico em um documento do Word

Spire.Doc for .NET fornece um método RemoveAt() em ParagraphCollection para remover parágrafos.

As etapas detalhadas para remover um parágrafo específico são as seguintes:

  • Crie um objeto da classe Document.
  • Carregue um documento do Word usando o método Document.LoadFromFile().
  • Obtenha a primeira seção usando a propriedade Document.Section[].
  • Remova o quarto parágrafo usando o método Section.Paragraphs.RemoveAt().
  • Salve o documento usando o método Document.SaveToFile().
  • C#
  • VB.NET
using System;
    using Spire.Doc;
    
    namespace RemoveParagraphs
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Create an object of Document class
                Document document = new Document();
    
                //Load a Word document
                document.LoadFromFile("Sample.docx");
    
                //Get the first section
                Section section = document.Sections[0];
    
                //Remove the first paragraph in the section
                section.Paragraphs.RemoveAt(3);
    
                //Save the document
                document.SaveToFile("RemoveParagraphs.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Remove Paragraphs in a Word Document

Excluir todos os parágrafos de um documento do Word

Para remover todos os parágrafos, você pode usar o método Clear() em ParagraphCollection fornecido por Spire.Doc for .NET.

As etapas detalhadas são as seguintes:

  • Crie um objeto da classe Document.
  • Carregue um documento do Word usando o método Document.LoadFromFile().
  • Percorra todas as seções e remova todos os parágrafos de cada seção usando o método Section.Paragraphs.Clear().
  • Salve o documento usando o método Document.SaveToFile().
  • C#
  • VB.NET
using System;
    using Spire.Doc;
    
    namespace RemoveAllParagraphs
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Create an object of Document class
                Document document = new Document();
    
                //Load a Word document
                document.LoadFromFile("Sample.docx");
    
                //Loop through all sections
                foreach (Section section in document.Sections)
                {
                    //Remove all paragraphs in the section
                    section.Paragraphs.Clear();
                }
    
                //Save the document
                document.SaveToFile("RemoveAllParagraphs.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Remove Paragraphs in a Word Document

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 может потребоваться удалить некоторые абзацы. Например, после того, как вы скопировали в свой документ содержимое из Интернета с большим количеством лишних абзацев, вам необходимо удалить лишние абзацы и оставить только те, которые полезны. Удаление можно легко выполнить с помощью Spire.Doc for .NET путем программирования без необходимости использования другого программного обеспечения. В этой статье будут показаны подробные шаги удаление абзацев в документе Word с помощью Spire.Doc for .NET.

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

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

PM> Install-Package Spire.Doc

Удалить определенный абзац в документе Word

Spire.Doc for .NET предоставляет метод RemoveAt() в коллекции ParagraphCollection для удаления абзацев.

Подробные шаги по удалению определенного абзаца следующие:

  • Создайте объект класса Document.
  • Загрузите документ Word с помощью метода Document.LoadFromFile().
  • Получите первый раздел, используя свойство Document.Section[].
  • Удалите четвёртый абзац, используя метод Раздел.Параграфы.RemoveAt().
  • Сохраните документ, используя метод Document.SaveToFile().
  • C#
  • VB.NET
using System;
    using Spire.Doc;
    
    namespace RemoveParagraphs
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Create an object of Document class
                Document document = new Document();
    
                //Load a Word document
                document.LoadFromFile("Sample.docx");
    
                //Get the first section
                Section section = document.Sections[0];
    
                //Remove the first paragraph in the section
                section.Paragraphs.RemoveAt(3);
    
                //Save the document
                document.SaveToFile("RemoveParagraphs.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Remove Paragraphs in a Word Document

Удалить все абзацы в документе Word

Чтобы удалить все абзацы, вы можете использовать метод Clear() в коллекции ParagraphCollection, предоставляемый Spire.Doc for .NET.

Подробные шаги следующие:

  • Создайте объект класса Document.
  • Загрузите документ Word с помощью метода Document.LoadFromFile().
  • Прокрутите все разделы и удалите все абзацы в каждом разделе, используя метод Раздел.Параграфы.Очистить().
  • Сохраните документ, используя метод Document.SaveToFile().
  • C#
  • VB.NET
using System;
    using Spire.Doc;
    
    namespace RemoveAllParagraphs
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Create an object of Document class
                Document document = new Document();
    
                //Load a Word document
                document.LoadFromFile("Sample.docx");
    
                //Loop through all sections
                foreach (Section section in document.Sections)
                {
                    //Remove all paragraphs in the section
                    section.Paragraphs.Clear();
                }
    
                //Save the document
                document.SaveToFile("RemoveAllParagraphs.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Remove Paragraphs in a Word Document

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

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

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

Beim Bearbeiten eines Word-Dokuments müssen Sie möglicherweise einige Absätze entfernen. Nachdem Sie beispielsweise Inhalte mit vielen überflüssigen Absätzen aus dem Internet in Ihr Dokument kopiert haben, müssen Sie die zusätzlichen Absätze löschen und nur diejenigen behalten, die nützlich sind. Das Löschen kann mit Spire.Doc for .NET einfach durch Programmierung erfolgen, ohne dass andere Software erforderlich ist. Dieser Artikel zeigt Ihnen die detaillierten Schritte von Entfernen von Absätzen in einem Word-Dokument mit Spire.Doc for .NET.

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

Löschen Sie einen bestimmten Absatz in einem Word-Dokument

Spire.Doc for .NET bietet unter ParagraphCollection eine Methode RemoveAt() zum Entfernen von Absätzen.

Die detaillierten Schritte zum Entfernen eines bestimmten Absatzes sind wie folgt:

  • Erstellen Sie ein Objekt der Document-Klasse.
  • Laden Sie ein Word-Dokument mit der Methode Document.LoadFromFile().
  • Rufen Sie den ersten Abschnitt mit der Eigenschaft Document.Section[] ab.
  • Entfernen Sie den 4. Absatz mit der Methode Section.Paragraphs.RemoveAt().
  • Speichern Sie das Dokument mit der Methode Document.SaveToFile().
  • C#
  • VB.NET
using System;
    using Spire.Doc;
    
    namespace RemoveParagraphs
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Create an object of Document class
                Document document = new Document();
    
                //Load a Word document
                document.LoadFromFile("Sample.docx");
    
                //Get the first section
                Section section = document.Sections[0];
    
                //Remove the first paragraph in the section
                section.Paragraphs.RemoveAt(3);
    
                //Save the document
                document.SaveToFile("RemoveParagraphs.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Remove Paragraphs in a Word Document

Löschen Sie alle Absätze in einem Word-Dokument

Um alle Absätze zu entfernen, können Sie die Methode Clear() unter ParagraphCollection verwenden, die von Spire.Doc for .NET bereitgestellt wird.

Die detaillierten Schritte sind wie folgt:

  • Erstellen Sie ein Objekt der Document-Klasse.
  • Laden Sie ein Word-Dokument mit der Methode Document.LoadFromFile().
  • Durchlaufen Sie alle Abschnitte und entfernen Sie alle Absätze in jedem Abschnitt mit der Methode Section.Paragraphs.Clear().
  • Speichern Sie das Dokument mit der Methode Document.SaveToFile().
  • C#
  • VB.NET
using System;
    using Spire.Doc;
    
    namespace RemoveAllParagraphs
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Create an object of Document class
                Document document = new Document();
    
                //Load a Word document
                document.LoadFromFile("Sample.docx");
    
                //Loop through all sections
                foreach (Section section in document.Sections)
                {
                    //Remove all paragraphs in the section
                    section.Paragraphs.Clear();
                }
    
                //Save the document
                document.SaveToFile("RemoveAllParagraphs.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Remove Paragraphs in a Word Document

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

Instalado a través de NuGet

PM> Install-Package Spire.Doc

enlaces relacionados

Al procesar un documento de Word, es posible que deba eliminar algunos párrafos. Por ejemplo, después de copiar contenidos de Internet con muchos párrafos redundantes a su documento, debe eliminar los párrafos adicionales y conservar solo aquellos que sean útiles. Spire.Doc for .NET puede lograr fácilmente la eliminación mediante programación sin necesidad de otro software. Este artículo le mostrará los pasos detallados de eliminar párrafos en un documento de Word usando 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

Eliminar un párrafo específico en un documento de Word

Spire.Doc for .NET proporciona un método RemoveAt() en ParagraphCollection para eliminar párrafos.

Los pasos detallados para eliminar un párrafo específico son los siguientes:

  • Crea un objeto de clase Documento.
  • Cargue un documento de Word utilizando el método Document.LoadFromFile().
  • Obtenga la primera sección usando la propiedad Document.Section[].
  • Elimine el cuarto párrafo utilizando el método Sección.Paragraphs.RemoveAt().
  • Guarde el documento utilizando el método Document.SaveToFile().
  • C#
  • VB.NET
using System;
    using Spire.Doc;
    
    namespace RemoveParagraphs
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Create an object of Document class
                Document document = new Document();
    
                //Load a Word document
                document.LoadFromFile("Sample.docx");
    
                //Get the first section
                Section section = document.Sections[0];
    
                //Remove the first paragraph in the section
                section.Paragraphs.RemoveAt(3);
    
                //Save the document
                document.SaveToFile("RemoveParagraphs.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Remove Paragraphs in a Word Document

Eliminar todos los párrafos de un documento de Word

Para eliminar todos los párrafos, puede utilizar el método Clear() en ParagraphCollection proporcionado por Spire.Doc for .NET.

Los pasos detallados son los siguientes:

  • Crea un objeto de clase Documento.
  • Cargue un documento de Word utilizando el método Document.LoadFromFile().
  • Recorra todas las secciones y elimine todos los párrafos de cada sección utilizando el método Sección.Paragraphs.Clear().
  • Guarde el documento utilizando el método Document.SaveToFile().
  • C#
  • VB.NET
using System;
    using Spire.Doc;
    
    namespace RemoveAllParagraphs
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Create an object of Document class
                Document document = new Document();
    
                //Load a Word document
                document.LoadFromFile("Sample.docx");
    
                //Loop through all sections
                foreach (Section section in document.Sections)
                {
                    //Remove all paragraphs in the section
                    section.Paragraphs.Clear();
                }
    
                //Save the document
                document.SaveToFile("RemoveAllParagraphs.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Remove Paragraphs in a Word Document

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

Wednesday, 27 September 2023 05:51

C#/VB.NET: Word 문서에서 단락 제거

NuGet을 통해 설치됨

PM> Install-Package Spire.Doc

관련된 링크들

Word 문서를 처리할 때 일부 단락을 제거해야 할 수도 있습니다. 예를 들어, 중복되는 단락이 많은 인터넷의 내용을 문서에 복사한 후 추가 단락을 삭제하고 유용한 단락만 유지해야 합니다. 삭제는 다른 소프트웨어 없이 프로그래밍하여 Spire.Doc for .NET을 통해 쉽게 수행할 수 있습니다. 이 기사에서는 자세한 단계를 보여줍니다 Word 문서에서 단락 제거 Spire.Doc for .NET을 사용합니다.

Spire.Doc for .NET 설치

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

PM> Install-Package Spire.Doc

Word 문서에서 특정 단락 삭제

Spire.Doc for .NET 단락을 제거하기 위해 ParagraphCollection 아래에 RemoveAt() 메서드를 제공합니다.

특정 단락을 제거하는 세부 단계는 다음과 같습니다.

  • Document 클래스의 객체를 생성합니다.
  • Document.LoadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
  • Document.Section[] 속성을 사용하여 첫 번째 섹션을 가져옵니다.
  • Section.Paragraphs.RemoveAt() 메서드를 사용하여 네 번째 단락을 제거합니다.
  • Document.SaveToFile() 메서드를 사용하여 문서를 저장합니다.
  • C#
  • VB.NET
using System;
    using Spire.Doc;
    
    namespace RemoveParagraphs
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Create an object of Document class
                Document document = new Document();
    
                //Load a Word document
                document.LoadFromFile("Sample.docx");
    
                //Get the first section
                Section section = document.Sections[0];
    
                //Remove the first paragraph in the section
                section.Paragraphs.RemoveAt(3);
    
                //Save the document
                document.SaveToFile("RemoveParagraphs.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Remove Paragraphs in a Word Document

Word 문서에서 모든 단락 삭제

모든 단락을 제거하려면 Spire.Doc for .NET에서 제공하는 ParagraphCollection 아래의 Clear() 메서드를 사용하면 됩니다.

자세한 단계는 다음과 같습니다.

  • Document 클래스의 객체를 생성합니다.
  • Document.LoadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
  • 모든 섹션을 반복하고 Section.Paragraphs.Clear() 메서드를 사용하여 각 섹션의 모든 단락을 제거합니다.
  • Document.SaveToFile() 메서드를 사용하여 문서를 저장합니다.
  • C#
  • VB.NET
using System;
    using Spire.Doc;
    
    namespace RemoveAllParagraphs
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Create an object of Document class
                Document document = new Document();
    
                //Load a Word document
                document.LoadFromFile("Sample.docx");
    
                //Loop through all sections
                foreach (Section section in document.Sections)
                {
                    //Remove all paragraphs in the section
                    section.Paragraphs.Clear();
                }
    
                //Save the document
                document.SaveToFile("RemoveAllParagraphs.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Remove Paragraphs in a Word Document

임시 라이센스 신청

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

또한보십시오

Durante l'elaborazione di un documento Word, potrebbe essere necessario rimuovere alcuni paragrafi. Ad esempio, dopo aver copiato nel documento contenuti da Internet con molti paragrafi ridondanti, è necessario eliminare i paragrafi extra e conservare solo quelli utili. La cancellazione può essere facilmente ottenuta da Spire.Doc for .NET programmando senza bisogno di altri software. Questo articolo ti mostrerà i passaggi dettagliati di rimuovere paragrafi in un documento Word utilizzando Spire.Doc for .NET.

Installa Spire.Doc for .NET

Per cominciare, devi aggiungere i file DLL inclusi nel pacchetto Spire.Doc for.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

Elimina un paragrafo specifico in un documento di Word

Spire.Doc for .NET fornisce un metodo RemoveAt() in ParagraphCollection per rimuovere i paragrafi.

I passaggi dettagliati per rimuovere un paragrafo specifico sono i seguenti:

  • Crea un oggetto della classe Document.
  • Carica un documento Word utilizzando il metodo Document.LoadFromFile().
  • Ottieni la prima sezione utilizzando la proprietà Document.Section[].
  • Rimuovi il quarto paragrafo utilizzando il metodo Sezione.Paragraphs.RemoveAt().
  • Salva il documento utilizzando il metodo Document.SaveToFile().
  • C#
  • VB.NET
using System;
    using Spire.Doc;
    
    namespace RemoveParagraphs
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Create an object of Document class
                Document document = new Document();
    
                //Load a Word document
                document.LoadFromFile("Sample.docx");
    
                //Get the first section
                Section section = document.Sections[0];
    
                //Remove the first paragraph in the section
                section.Paragraphs.RemoveAt(3);
    
                //Save the document
                document.SaveToFile("RemoveParagraphs.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Remove Paragraphs in a Word Document

Elimina tutti i paragrafi in un documento di Word

Per rimuovere tutti i paragrafi, è possibile utilizzare il metodo Clear() in ParagraphCollection fornito da Spire.Doc for .NET.

I passaggi dettagliati sono i seguenti:

  • Crea un oggetto della classe Document.
  • Carica un documento Word utilizzando il metodo Document.LoadFromFile().
  • Passa in rassegna tutte le sezioni e rimuovi tutti i paragrafi in ciascuna sezione utilizzando il metodo Sezione.Paragraphs.Clear().
  • Salva il documento utilizzando il metodo Document.SaveToFile().
  • C#
  • VB.NET
using System;
    using Spire.Doc;
    
    namespace RemoveAllParagraphs
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Create an object of Document class
                Document document = new Document();
    
                //Load a Word document
                document.LoadFromFile("Sample.docx");
    
                //Loop through all sections
                foreach (Section section in document.Sections)
                {
                    //Remove all paragraphs in the section
                    section.Paragraphs.Clear();
                }
    
                //Save the document
                document.SaveToFile("RemoveAllParagraphs.docx", FileFormat.Docx2013);
            }
        }
    }

C#/VB.NET: Remove Paragraphs in a Word Document

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