How to Convert Word (DOC or DOCX) to PDF in C# .NET

Converting Word documents to PDF is a common requirement in many C# applications, but relying on Microsoft Office Interop can be cumbersome and inefficient. Fortunately, third-party libraries like Spire.Doc for .NET provide a powerful and seamless alternative for high-quality conversions without Interop dependencies. Whether you need to preserve formatting, secure PDFs with passwords, or optimize file size, Spire.Doc offers a flexible solution with minimal code.
In this guide, we’ll explore how to convert Word to PDF in C# using Spire.Doc, covering basic conversions, advanced customization, and best practices for optimal results.
- C# .NET Library for Converting Word to PDF
- Basic DOCX to PDF Conversion Example
- Advanced Word to PDF Conversion Options
- Adjust Word Documents for Optimal Conversion
- Conclusion
- FAQs
C# .NET Library for Converting Word to PDF
Spire.Doc for .NET is a robust API that enables developers to create, edit, and convert Word documents programmatically. It supports converting Word (DOC, DOCX) to PDF while preserving formatting, images, hyperlinks, and other elements.
With Spire.Doc, you can benefit from:
- High-fidelity conversion with minimal formatting loss
- Support for password-protected PDFs
- Customizable PDF settings (PDF/A compliance, font embedding, etc.)
- Batch conversion of multiple Word files
To get started, download Spire.Doc from the official website and reference the DLLs in your project. Or, you can install it via NuGet through the following command:
PM> Install-Package Spire.Doc
Basic DOCX to PDF Conversion Example
Converting Word documents to PDFs using Spire.Doc is a simple process that requires minimal code. The following example demonstrates how to load a DOCX file and save it as a PDF with default settings.
- C#
using Spire.Doc;
namespace ConvertWordToPdf
{
class Program
{
static void Main(string[] args)
{
// Create a Document object
Document doc = new Document();
// Load a Word document
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.docx");
// Save the document to PDF
doc.SaveToFile("ToPDF.pdf", FileFormat.PDF);
// Dispose resources
doc.Dispose();
}
}
}
In this example:
- A Document object is instantiated to manage the Word file.
- The LoadFromFile method loads the DOCX file from the specified path.
- The SaveToFile method converts and saves the document in PDF format.
- Finally, the Dispose method is called to release resources used by the Document object.
This straightforward approach allows for quick and efficient conversion of DOCX files into PDFs with just a few lines of code.
Result:

Advanced Word to PDF Conversion Options
To gain greater control over the conversion process, Spire.Doc offers the ToPdfParameterList class. With this class, you can:
- Convert to PDF/A (a standardized archival format)
- Apply password protection and permission restrictions
- Embed fonts to ensure consistent rendering
- Preserve bookmarks for better navigation
- Disable hyperlinks if necessary
Here’s a summary of available options:
| Option | Implemented by |
| Convert to PDF/A | PdfConformanceLevel |
| Protect PDF with a passoword | PdfSecurity |
| Restrict permessions (e.g., printing) | PdfSecurity |
| Embed all fonts | IsEmbeddedAllFonts |
| Embed specific fonts | EmbeddedFontNameList |
| Preserve bookmarks | CreateWordsBookmarks |
| Create bookmarks from headings | CreateWordBookmarksUsingHeadings |
| Disable hyperlinks | DisableLink |
Example 1: Convert Word to Password-Protected PDF
When sharing confidential Word documents as PDFs, a simple conversion isn't enough. Spire.Doc lets you add military-grade password protection by using the PdfSecurity.Encrypt method, preventing unauthorized access while maintaining perfect formatting.
The following code encrypts the generated PDF document with an open password:
- C#
using Spire.Doc;
namespace ConvertWordToPasswordProtectedPdf
{
class Program
{
static void Main(string[] args)
{
// Create a Document object
Document doc = new Document();
// Load a Word document
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.docx");
// Create a ToPdfParameterList object
ToPdfParameterList parameters = new ToPdfParameterList();
// Set an open password
parameters.PdfSecurity.Encrypt("openPsd");
// Save the Word to PDF with options
doc.SaveToFile("PasswordProtected.pdf", parameters);
// Dispose resources
doc.Dispose();
}
}
}
Advanced Contol:
Want even more control? Combine with document permessions:
- C#
parameters.PdfSecurity.Encrypt("openPsd", "permissionPsd", PdfPermissionsFlags.Print, PdfEncryptionKeySize.Key128Bit);
doc.SaveToFile("PasswordProtected.pdf", parameters);
Example 2: Ensure Consistent Text Rendering by Embedding Fonts in PDF
When converting Word to PDF, fonts may appear differently (or even as gibberish) if the viewer’s system lacks the original fonts used in your document. Spire.Doc solves this by embedding fonts directly into the PDF, guaranteeing that text displays exactly as intended—regardless of the device or software used to open the file.
The following code embeds all fonts when converting Word to PDF in C#:
- C#
using Spire.Doc;
namespace EmbedFonts
{
class Program
{
static void Main(string[] args)
{
// Create a Document object
Document doc = new Document();
// Load a Word document
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");
// Create a ToPdfParameterList object
ToPdfParameterList parameters = new ToPdfParameterList();
// Embed all the fonts used in Word in the generated PDF
parameters.IsEmbeddedAllFonts = true;
// Save the document to PDF
doc.SaveToFile("EmbedFonts.pdf", parameters);
// Dispose resources
doc.Dispose();
}
}
}
Advanced Contol:
To reduce file size, you can selectively embed fonts (e.g., only your custom font, not common ones like Arial):
- C#
parameters.PrivateFontPaths = new List()
{
new PrivateFontPath("YourCustomFont", "FontPath"),
new PrivateFontPath("AnotherFont", "FontPath")
};
doc.SaveToFile("EmbedCustomFonts.pdf", parameters);
Adjust Word Documents for Optimal Conversion
To achieve the best PDF output, you may need to prepare your Word document before conversion. Consider the following adjustments:
- Change page size or margins for better layout
- Enhance document security by adding watermarks
- Compress images to reduce file size
Example: Reduce PDF Size by Compressing Images
Large image-heavy Word documents often create bloated PDFs that are difficult to share. With Spire.Doc, you can automatically optimize images during conversion, dramatically reducing file size while maintaining acceptable quality.
The following code reduces image quality to 50%, resulting in a smaller PDF:
- C#
using Spire.Doc;
namespace SetImageQualityWhenConverting
{
class Program
{
static void Main(string[] args)
{
// Create a Document object
Document doc = new Document();
// Load a Word document
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.docx");
// Reduce image quality to 50%
doc.JPEGQuality = 50;
// Save the document to PDF
doc.SaveToFile("CompressImage.pdf", FileFormat.PDF);
// Dispose resources
doc.Dispose();
}
}
}
Conclusion
Converting Word documents to PDF in C# doesn’t have to be complicated—Spire.Doc for .NET simplifies the process and offers extensive customization options, from basic conversions to advanced features like PDF encryption, font embedding, and image compression, all without Interop.
By following the techniques outlined in this guide, you can efficiently integrate Word-to-PDF functionality into your applications. For further assistance, explore Spire.Doc’s documentation or leverage its free trial to test its capabilities.
FAQs
Q1: How do I convert multiple Word files to PDFs in C#?
A: You can create a loop in your code to process multiple files at once. For example:
- C#
string[] files = Directory.GetFiles("input_folder", "*.docx");
foreach (string file in files)
{
Document document = new Document();
document.LoadFromFile(file);
document.SaveToPDF(Path.ChangeExtension(file, ".pdf"), FileFormat.PDF);
document.Dispose();
}
Q2: How to merge multiple Word files into a single PDF?
A: You can merge Word files first (using Spire.Doc), and then convert the combined document to PDF. For example:
- C#
Document mergedDoc = new Document();
string[] filesToMerge = Directory.GetFiles("input_folder ", "*.docx");
foreach (string file in filesToMerge)
{
mergedDoc.InsertTextFromFile(file, FileFormat.Docx);
}
mergedDoc.SaveToFile("Merged.pdf", FileFormat.PDF);
mergedDoc.Dispose();
Q3: Why is my converted PDF missing text or formatting?
A: This issue may arise from missing custom fonts on your system. To resolve it, install the required fonts on the machine performing the conversion. Alternatively, you can embed the fonts directly into the PDF using Spire.Doc during the conversion process.
Q4: Is Spire.Doc free for Word-to-PDF conversion?
A: No, Spire.Doc is a paid library. However, a free version is available with limited functionality, allowing users to convert only the first three pages of a Word document to PDF. This option is ideal for small projects or personal use.
Get a Free License
To fully experience the capabilities of Spire.Doc for .NET without any evaluation limitations, you can request a free 30-day trial license.
Insert Image Header and Footer for Word
Word header and footer presents additional information of Word document, which can be text, image or page number. This guide focuses on introducing how to insert image header and footer for Word document in C# and VB.NET.
Header/Footer plays an important role in Word document, which uses text, image or page number to demonstrate some additional information about this document. The information can be company name, logo, author name, document title etc. This guide will demonstrate detailed process to insert image header/footer in Word with C# and VB.NET via Spire.Doc for .NET. The following screenshot displays Word image header/footer result after programming.

Spire.Doc for .NET provides a HeaderFooter. class to enable developers to generate a new header or footer. Firstly, initialize a header instance of HeaderFooter class and then invoke AddParagraph() method to add a paragraph body for this header/footer instance. Next, invoke Paragraph.AppendPicture(Image image) method to append a picture for header/footer paragraph. If you want to add text for paragraph as well, please invoke Paragraph.AppendText(string text) method. Also, you can set format for header/footer paragraph, appended image and text to have a better layout. Code as following:
using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace ImageHeaderFooter
{
class Program
{
static void Main(string[] args)
{
//Load Document
Document document = new Document();
document.LoadFromFile(@"E:\Work\Documents\Spire.Doc for .NET.docx");
//Initialize a Header Instance
HeaderFooter header = document.Sections[0].HeadersFooters.Header;
//Add Header Paragraph and Format
Paragraph paragraph = header.AddParagraph();
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Right;
//Append Picture for Header Paragraph and Format
DocPicture headerimage = paragraph.AppendPicture(Image.FromFile(@"E:\Logo\doclog.png"));
headerimage.VerticalAlignment = ShapeVerticalAlignment.Bottom;
//Initialize a Footer Instance
HeaderFooter footer = document.Sections[0].HeadersFooters.Footer;
//Add Footer Paragraph and Format
Paragraph paragraph2 = footer.AddParagraph();
paragraph2.Format.HorizontalAlignment = HorizontalAlignment.Left;
//Append Picture and Text for Footer Paragraph
DocPicture footerimage = paragraph2.AppendPicture(Image.FromFile(@"E:\Logo\logo.jpeg"));
TextRange TR = paragraph2.AppendText("Copyright © 2013 e-iceblue. All Rights Reserved.");
TR.CharacterFormat.FontName = "Arial";
TR.CharacterFormat.FontSize = 10;
TR.CharacterFormat.TextColor = Color.Black;
//Save and Launch
document.SaveToFile("ImageHeaderFooter.docx", FileFormat.Docx);
System.Diagnostics.Process.Start("ImageHeaderFooter.docx");
}
}
}
Imports System.Drawing
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields
Namespace ImageHeaderFooter
Friend Class Program
Shared Sub Main(ByVal args() As String)
'Load Document
Dim document As New Document()
document.LoadFromFile("E:\Work\Documents\Spire.Doc for .NET.docx")
'Initialize a Header Instance
Dim header As HeaderFooter = document.Sections(0).HeadersFooters.Header
'Add Header Paragraph and Format
Dim paragraph As Paragraph = header.AddParagraph()
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Right
'Append Picture for Header Paragraph and Format
Dim headerimage As DocPicture = paragraph.AppendPicture(Image.FromFile("E:\Logo\doclog.png"))
headerimage.VerticalAlignment = ShapeVerticalAlignment.Bottom
'Initialize a Footer Instance
Dim footer As HeaderFooter = document.Sections(0).HeadersFooters.Footer
'Add Footer Paragraph and Format
Dim paragraph2 As Paragraph = footer.AddParagraph()
paragraph2.Format.HorizontalAlignment = HorizontalAlignment.Left
'Append Picture and Text for Footer Paragraph
Dim footerimage As DocPicture = paragraph2.AppendPicture(Image.FromFile("E:\Logo\logo.jpeg"))
Dim TR As TextRange = paragraph2.AppendText("Copyright © 2013 e-iceblue. All Rights Reserved.")
TR.CharacterFormat.FontName = "Arial"
TR.CharacterFormat.FontSize = 10
TR.CharacterFormat.TextColor = Color.Black
'Save and Launch
document.SaveToFile("ImageHeaderFooter.docx", FileFormat.Docx)
System.Diagnostics.Process.Start("ImageHeaderFooter.docx")
End Sub
End Class
End Namespace
Spire.Doc, an easy-to-use component to perform Word tasks, allows developers to fast generate, write, edit and save Word (Word 97-2003, Word 2007, Word 2010) in C# and VB.NET for .NET, Silverlight and WPF.
C#/VB.NET: Align Text in Word
Text alignment is a paragraph formatting attribute that determines the appearance of the text in a whole paragraph. There are four types of text alignments available in Microsoft Word: left-aligned, center-aligned, right-aligned, and justified. In this article, you will learn how to programmatically set different text alignments for 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
Align Text in Word
The detailed steps are as follows:
- Create a Document instance.
- Load a sample Word document using Document.LoadFromFile() method.
- Get a specified section using Document.Sections[] property.
- Get a specified paragraph using Section.Paragraphs[] property.
- Get the paragraph format using Paragraph.Format property
- Set text alignment for the specified paragraph using ParagraphFormat.HorizontalAlignment property.
- Save the document to another file using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
namespace AlignText
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document doc = new Document();
//Load a sample Word document
doc.LoadFromFile(@"D:\Files\sample.docx");
//Get the first section
Section section = doc.Sections[0];
//Get the first paragraph and make it center-aligned
Paragraph p = section.Paragraphs[0];
p.Format.HorizontalAlignment = HorizontalAlignment.Center;
//Get the second paragraph and make it left-aligned
Paragraph p1 = section.Paragraphs[1];
p1.Format.HorizontalAlignment = HorizontalAlignment.Left;
//Get the third paragraph and make it right-aligned
Paragraph p2 = section.Paragraphs[2];
p2.Format.HorizontalAlignment = HorizontalAlignment.Right;
//Get the fourth paragraph and make it justified
Paragraph p3 = section.Paragraphs[3];
p3.Format.HorizontalAlignment = HorizontalAlignment.Justify;
//Save the document
doc.SaveToFile("WordAlignment.docx", FileFormat.Docx);
}
}
}

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.
C#: Set Fonts when Creating a New Word Document
When creating a new Word document, setting the appropriate fonts is crucial for establishing tone and enhancing readability. Fonts influence how your content is perceived, whether for formal reports, creative projects, or casual notes. By selecting the right typeface and size, you can ensure your document is not only visually appealing but also effective in communicating your message.
In this article, you will learn how to set fonts when creating a new Word document in C# using Spire.Doc for .NET.
- Set the Font for a Paragraph in C#
- Apply Different Fonts to Text in C#
- Use a Custom Font in a Word Document in C#
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
Set the Font for a Paragraph in C#
Setting fonts is a fundamental task when working with Word documents in C#. Spire.Doc offers the ParagraphStyle class, which lets you specify font family, size, style, and text color. Once you've created a style, you can apply it to format a paragraph with the desired settings.
The detailed steps to set the font for a paragraph using C# are as follows:
- Create a Document object.
- Add a section and a paragraph to the document.
- Append text to the paragraph.
- Create a ParagraphStyle object.
- Get the CharacterFormat object through the ParagraphStyle.CharacterFormat property.
- Set the font style, name, size and text color using the properties under the CharacterFormat object.
- Add the style to the document using the Document.Styles.Add() method.
- Apply the defined style to the paragraph using the Paragraph.ApplyStyle() method.
- Save the document to a Word file.
Here is an example that demonstrates how to set the font for a paragraph when creating a new Word document in C#:
- C#
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
namespace SetFontForParagraph
{
class Program
{
static void Main(string[] args)
{
// Create a Document object
Document doc = new Document();
// Add a section
Section section = doc.AddSection();
// Set the page margins
section.PageSetup.Margins.All = 40f;
// Add a paragraph
Paragraph paragraph = section.AddParagraph();
// Append text to the paragraph
paragraph.AppendText("Spire.Doc for .NET is a powerful library designed for developers " +
"working with document processing in the .NET environment. It enables users to create, " +
"read, modify, and convert various types of document formats, such as DOC, DOCX, PDF, " +
"and more, without the need for Microsoft Office installed on the machine.");
// Create a ParagraphStyle object
ParagraphStyle style = new ParagraphStyle(doc);
// Set the style name
style.Name = "myStyle";
// Set the font style, name, size and text color
style.CharacterFormat.Bold = false;
style.CharacterFormat.TextColor = Color.Black;
style.CharacterFormat.FontName = "Times New Roman";
style.CharacterFormat.FontSize = 14;
// Add the style the document
doc.Styles.Add(style);
// Apply the style to the paragraph
paragraph.ApplyStyle(style.Name);
// Set the horizontal alignment
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Left;
// Save the document to a docx file
doc.SaveToFile("SetFont.docx", FileFormat.Docx2019);
// Dispose resources
doc.Dispose();
}
}
}

Apply Different Fonts to Text in C#
In some cases, you may need to apply various fonts to different segments of the same paragraph. Spire.Doc offers the TextRange class, which allows you to assign distinct styles to specific text ranges within a paragraph. To do this, ensure that the text requiring different styles is organized into separate text ranges.
The steps to apply multiple fonts in a paragraph using C# are as follows:
- Create a Document object.
- Add a section and a paragraph to the document.
- Append text to the paragraph using the Paragraph.AppendText() method, which returns a TextRange object.
- Append more text that needs to be styled differently to the paragraph and return different TextRange objects.
- Create a ParagraphStyle object with the basic font information and apply it to the paragraph.
- Change the font name, style, size and text color of the specified text range using the properties under the specific TextRange object.
- Save the document to a Word file.
Here's an example that demonstrates how to apply different fonts to different parts of a paragraph:
- C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;
namespace ApplyDifferentFontsToText
{
class Program
{
static void Main(string[] args)
{
// Create a Document object
Document doc = new Document();
// Add a section
Section section = doc.AddSection();
// Set the page margins
section.PageSetup.Margins.All = 40f;
// Add a paragraph
Paragraph paragraph = section.AddParagraph();
// Append text to the paragraph
TextRange textRange1 = paragraph.AppendText("Spire.Doc for .NET");
TextRange textRange2 = paragraph.AppendText(" is a powerful library designed for developers " +
"working with document processing in the .NET environment. It enables users to ");
TextRange textRange3 = paragraph.AppendText("create, read, modify, and convert");
TextRange textRange4 = paragraph.AppendText(" various types of document formats, such as ");
TextRange textRange5 = paragraph.AppendText("DOC, DOCX, PDF");
TextRange textRange6 = paragraph.AppendText(" and more, without the need for Microsoft Office installed on the machine.");
// Create a ParagraphStyle object
ParagraphStyle style = new ParagraphStyle(doc);
// Set the style name
style.Name = "myStyle";
// Set the font style, name, size and text color
style.CharacterFormat.Bold = false;
style.CharacterFormat.TextColor = Color.Black;
style.CharacterFormat.FontName = "Times New Roman";
style.CharacterFormat.FontSize = 14;
// Add the style the document
doc.Styles.Add(style);
// Apply the style to the paragraph
paragraph.ApplyStyle(style.Name);
// Change the font style of the specified text ranges
textRange1.CharacterFormat.Bold = true;
textRange1.CharacterFormat.TextColor = Color.Purple;
textRange3.CharacterFormat.Bold = true;
textRange3.CharacterFormat.TextColor = Color.Purple;
textRange5.CharacterFormat.Bold = true;
textRange5.CharacterFormat.TextColor = Color.Purple;
// Set the horizontal alignment
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Left;
// Save the document to a docx file
doc.SaveToFile("ApplyDifferentFonts.docx", FileFormat.Docx2019);
// Dispose resources
doc.Dispose();
}
}
}

Use a Custom Font in a Word Document in C#
Spire.Doc supports custom fonts, allowing you to use fonts that are not installed on the system where the application is running. To use a custom font, you need to embed the font file in your application and then specify it in your code.
The steps to utilize custom fonts in a Word document are as follows:
- Create a Document object.
- Add a section and a paragraph to the document.
- Append text to the paragraph.
- Set the custom fonts for the document using the Document.SetCustomFonts() method.
- Embed fonts in the generated file by setting the Document.EmbedFontsInFile property to true.
- Create a ParagraphStyle object.
- Set the font name to your custom font using the ParagraphStyle.CharacterFormat.FontName property.
- Apply the style to the paragraph using the Paragraph.ApplyStyle() method.
- Save the document to a Word file.
Here's an example that demonstrates how to use a custom font:
- C#
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
namespace SetFontForParagraph
{
class Program
{
static void Main(string[] args)
{
// Create a Document object
Document doc = new Document();
// Add a section
Section section = doc.AddSection();
// Set the page margins
section.PageSetup.Margins.All = 40f;
// Add a paragraph
Paragraph paragraph = section.AddParagraph();
// Append text to the paragraph
paragraph.AppendText("Spire.Doc for .NET is a powerful library designed for developers " +
"working with document processing in the .NET environment. It enables users to create, " +
"read, modify, and convert various types of document formats, such as DOC, DOCX, PDF, " +
"and more, without the need for Microsoft Office installed on the machine.");
// Specify the private font path
string fontPath = "C:\\Users\\Administrator\\Desktop\\Super Morning.ttf";
// Create an array of Stream objects to hold the font streams
Stream[] fontStreams = new Stream[1];
fontStreams[0] = new FileStream(fontPath, FileMode.Open, FileAccess.Read);
// Set the custom fonts for the document
doc.SetCustomFonts(fontStreams);
// Embed fonts in the generated file
doc.EmbedFontsInFile = true;
// Create a ParagraphStyle object
ParagraphStyle style = new ParagraphStyle(doc);
// Set the paragraph style name
style.Name = "myStyle";
// Set the font name as the name of the private font
style.CharacterFormat.FontName = "Super Morning";
// Set the font style, size and text color
style.CharacterFormat.Bold = false;
style.CharacterFormat.TextColor = Color.Black;
style.CharacterFormat.FontSize = 14;
// Add the style the document
doc.Styles.Add(style);
// Apply the defined style to the paragraph
paragraph.ApplyStyle(style.Name);
// Set the horizontal alignment
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Left;
// Save the document to a docx file
doc.SaveToFile("UseCustomFont.docx", FileFormat.Docx2019);
// Dispose resources
doc.Dispose();
}
}
}

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.
C#/VB.NET: Change Font Color in Word
If you want to emphasize a specific paragraph or text in your Word document, you can change its font color. This article will demonstrate how to change font color in Word in C# and VB.NET using Spire.Doc for .NET library.
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
Change Font Color of a Paragraph in C# and VB.NET
The following are the steps to change the font color of a paragraph in a Word document:
- Create a Document instance.
- Load the Word document using Document.LoadFromFile() method.
- Get the desired section using Document.Sections[sectionIndex] property.
- Get the desired paragraph that you want to change the font color of using Section.Paragraphs[paragraphIndex] property.
- Create a ParagraphStyle instance.
- Set the style name and font color using ParagraphStyle.Name and ParagraphStyle.CharacterFormat.TextColor properties.
- Add the style to the document using Document.Styles.Add() method.
- Apply the style to the paragraph using Paragraph.ApplyStyle() method.
- Save the result document using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
namespace ChangeFontColorForParagraph
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document document = new Document();
//Load a Word document
document.LoadFromFile("Sample.docx");
//Get the first section
Section section = document.Sections[0];
//Change text color of the first Paragraph
Paragraph p1 = section.Paragraphs[0];
ParagraphStyle s1 = new ParagraphStyle(document);
s1.Name = "Color1";
s1.CharacterFormat.TextColor = Color.RosyBrown;
document.Styles.Add(s1);
p1.ApplyStyle(s1.Name);
//Change text color of the second Paragraph
Paragraph p2 = section.Paragraphs[1];
ParagraphStyle s2 = new ParagraphStyle(document);
s2.Name = "Color2";
s2.CharacterFormat.TextColor = Color.DarkBlue;
document.Styles.Add(s2);
p2.ApplyStyle(s2.Name);
//Save the result document
document.SaveToFile("ChangeParagraphTextColor.docx", FileFormat.Docx);
}
}
}

Change Font Color of a Specific Text in C# and VB.NET
The following are the steps to change the font color of a specific text in a Word document:
- Create a Document instance.
- Load a Word document using Document.LoadFromFile() method.
- Find the text that you want to change font color of using Document.FindAllString() method.
- Loop through all occurrences of the searched text and change the font color for each occurrence using TextSelection.GetAsOneRange().CharacterFormat.TextColor Property.
- Save the result document using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
namespace ChangeFontColorForText
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document document = new Document();
//Load a Word document
document.LoadFromFile("Sample.docx");
//Find the text that you want to change font color for
TextSelection[] text = document.FindAllString("Spire.Doc for .NET", false, true);
//Change the font color for the searched text
foreach (TextSelection seletion in text)
{
seletion.GetAsOneRange().CharacterFormat.TextColor = Color.Red;
}
//Save the result document
document.SaveToFile("ChangeCertainTextColor.docx", FileFormat.Docx);
}
}
}

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.
C#: Find and Replace Text in Word Documents
When it comes to editing documents, making changes to the text is a common task. Microsoft Word provides a robust feature called "Find and Replace" that streamlines the text editing process. With this feature, you can effortlessly locate specific words, phrases, or characters within your document and replace them in one simple action. This eliminates the need for repetitive manual searching and time-consuming edits, saving you valuable time and effort, especially when you need to make widespread changes in lengthy documents. In this article, we will explain how to find and replace text in Word documents in C# using Spire.Doc for .NET.
- Find Text and Replace All Its Instances with New Text
- Find Text and Replace Its First Instance with New Text
- Find and Replace Text with Image
- Find and Replace Text using Regular Expression
- Find and Replace Text with Content from Another Word Document
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
Find Text and Replace All Its Instances with New Text
Spire.Doc for .NET provides the Document.Replace() method that enables you to find and replace specific text in a Word document. With this method, you can seamlessly replace all instances of the target text with new content. Additionally, you have the flexibility to specify whether the search should be case-sensitive and whether whole-word matching should be considered. The detailed steps are as follows.
- Instantiate an object of the Document class.
- Load a sample Word document using Document.LoadFromFile() method.
- Replace all instances of specific text with new text using Document.Replace(string matchString, string newValue, bool caseSensitive, bool wholeWord) method.
- Save the result document using Document.SaveToFile() method.
- C#
using Spire.Doc;
namespace ReplaceAllText
{
internal class Program
{
static void Main(string[] args)
{
//Instantiate an object of the Document class
Document document = new Document();
//Load a sample Word document
document.LoadFromFile("Sample.docx");
//Replace all instances of specific text with new text
document.Replace("Spire.Doc", "Eiceblue", false, true);
//Save the result document
document.SaveToFile("ReplaceAllText.docx", FileFormat.Docx2016);
document.Close();
}
}
}

Find Text and Replace Its First Instance with New Text
To replace the first instance of a specific text in a Word document using Spire.Doc for .NET, you can utilize the Document.ReplaceFirst property. By setting this property to true before calling the Document.Replace() method, you can change the text replacement mode to exclusively replace the first instance. The detailed steps are as follows.
- Instantiate an object of the Document class.
- Load a sample Word document using Document.LoadFromFile() method.
- Change the text replacement mode to replace the first instance only by setting the Document.ReplaceFirst property to true.
- Call the Document.Replace(string matchString, string newValue, bool caseSensitive, bool wholeWord) method to replace text.
- Save the result document using Document.SaveToFile() method.
- C#
using Spire.Doc;
namespace ReplaceFirstText
{
internal class Program
{
static void Main(string[] args)
{
//Instantiate an object of the Document class
Document document = new Document();
//Load a sample Word document
document.LoadFromFile("Sample.docx");
//Change the text replacement mode to replace the first instance only
document.ReplaceFirst = true;
//Replace the first instance of specific text with new text
document.Replace("Spire.Doc", "Eiceblue", false, true);
//Save the result document
document.SaveToFile("ReplaceFirstText.docx", FileFormat.Docx2016);
document.Close();
}
}
}
Find and Replace Text with Image
Sometimes, you may need to replace text with images for visual representation or design purposes. In Spire.Doc for .NET, replacing text with image can be achieved by inserting the image at the position of the target text and then removing the text from the document. The detailed steps are as follows.
- Instantiate an object of the Document class.
- Load a sample Word document using Document.LoadFromFile() method.
- Find specific text in the document using Document.FindAllString() method.
- Loop through the matched text.
- For each matched text, get the paragraph where it is located and get the position of the text in the paragraph.
- Instantiate an object of the DocPicture class, and then load an image using DocPicture.LoadImage() method.
- Insert the image into the paragraph at the position of the text and then remove the text from the paragraph.
- Save the result document using Document.SaveToFile() method.
- C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace ReplaceTextWithImage
{
internal class Program
{
static void Main(string[] args)
{
//Instantiate an object of the Document class
Document document = new Document();
//Load a sample Word document
document.LoadFromFile("Sample.docx");
//Find specific text in the document
TextSelection[] selections = document.FindAllString("Spire.Doc", true, true);
int index = 0;
Paragraph ownerParagraph = null;
//Loop through the matched text
foreach (TextSelection selection in selections)
{
//Get the paragraph where the text is located
ownerParagraph = selection.GetAsOneRange().OwnerParagraph;
//Get the index position of the text in the paragraph
index = ownerParagraph.ChildObjects.IndexOf(selection.GetAsOneRange());
//Load an image
DocPicture pic = new DocPicture(document);
pic.LoadImage("img.png");
//Insert the image into the paragraph at the index position of the text
ownerParagraph.ChildObjects.Insert(index, pic);
//Remove the text from the paragraph
ownerParagraph.ChildObjects.Remove(selection.GetAsOneRange());
}
//Save the result document
document.SaveToFile("ReplaceTextWithImage.docx", FileFormat.Docx2016);
document.Close();
}
}
}

Find and Replace Text using Regular Expression
Regular expressions offer a robust toolset for performing complex search and replace operations within documents. The Document.Replace() method can leverage regular expressions to search for specific text, allowing you to perform advanced search and replace operations based on specific criteria. The detailed steps are as follows.
- Instantiate an object of the Document class.
- Load a sample Word document using Document.LoadFromFile() method.
- Instantiate an object of the Regex class to match text based on specific criteria.
- Replace the matched text with new text using Document.Replace(Regex pattern, string replace) method.
- Save the resulting document using Document.SaveToFile() method.
- C#
using Spire.Doc;
using System.Text.RegularExpressions;
namespace ReplaceTextWithRegex
{
internal class Program
{
static void Main(string[] args)
{
//Instantiate an object of the Document class
Document document = new Document();
//Load a sample Word document
document.LoadFromFile("Sample.docx");
//Create a regex to match the text that starts with #
Regex regex = new Regex(@"\#\w+\b");
//Replace the matched text with new text
document.Replace(regex, "Spire.Doc");
//Save the result document
document.SaveToFile("ReplaceTextWithRegex.docx", FileFormat.Docx2016);
document.Close();
}
}
}
Find and Replace Text with Content from Another Word Document
In addition to replacing text with new text or image, Spire.Doc for .NET also enables you to replace text with content from another Word document. This can be beneficial when you are working on a predefined Word template and need to incorporate contents from other Word documents into it. The detailed steps are as follows.
- Instantiate an object of the Document class.
- Load a sample Word document using Document.LoadFromFile() method.
- Load another Word document into an IDocument object.
- Replace specific text in the sample document with content from another document using Document.Replace(string matchString, IDocument matchDoc, bool caseSensitive, bool wholeWord) method.
- Save the result document using Document.SaveToFile() method.
- C#
using Spire.Doc;
using Spire.Doc.Interface;
namespace ReplaceTextWithDocument
{
internal class Program
{
static void Main(string[] args)
{
//Instantiate an object of the Document class
Document document = new Document();
//Load a sample Word document
document.LoadFromFile("Template.docx");
//Load another Word document
IDocument document1 = new Document("Report.docx");
//Replace specific text in the sample document with content from another document
document.Replace("Annual Sales", document1, false, true);
//Save the result document
document.SaveToFile("ReplaceTextWithDocument.docx", FileFormat.Docx2016);
document.Close();
}
}
}
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.
C#/VB.NET: Convert Word to XML
XML is a markup language and file format designed mainly to store and transmit arbitrary content. XML files have the feature of simplicity, generality, and usability, making them popular, especially among web servers. XML and HTML are two important markup languages on the web, but XML focuses on storing and transmitting data while HTML focuses on displaying webpages. This article demonstrates how to convert Word documents to XML files with the help of 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
Convert a Word Document to an XML File
The detailed steps are as follows:
- Create an object of Document class.
- Load the Word document from disk using Document.LoadFromFile().
- Save the Word document as an XML file using Document.SaveToFile().
- C#
- VB.NET
using System;
using Spire.Doc;
namespace WordtoXML
{
internal class Program
{
static void Main(string[] args)
{
//Create an object of Document class
Document document = new Document();
//Load a Word document from disk
document.LoadFromFile(@"D:\testp\test.docx");
//Save the Word document as an XML file
document.SaveToFile("Sample.xml", FileFormat.Xml);
}
}
}

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.
C#/VB.NET: Insert Hyperlinks to Word Documents
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);
}
}
}

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);
}
}
}

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.
Encrypt Word with Custom Password in C#, VB.NET
Word encryption, one method to protect Word document, requires users to give the document a password. Without the password, encrypted document cannot be opened. Solution in this guide demonstrates how to encrypt Word document with custom password in C# and VB.NET via Spire.Doc for .NET.
Spire.Doc for .NET, specializing in performing Word processing tasks for .NET, provides a Document.Encrypt method which enables users to encrypt Word. The overload passed to this method is string password. Firstly, load the Word document which is needed to protect. Secondly, invoke Document.Encrypt method to encrypt with password. Thirdly, save the encrypt document and launch for viewing. After debugging, a dialog box pops up and requires the password. Enter the password to open the document and the document information will be shown as following to tell users that it is encrypted.

Download and install Spire.Doc for .NET and use the following code to encrypt Word.
using Spire.Doc;
namespace Encryption
{
class Program
{
static void Main(string[] args)
{
//Load Document
Document document = new Document();
document.LoadFromFile(@"E:\Work\Documents\WordDocuments\Spire.Doc for .NET.docx");
//Encrypt
document.Encrypt("eiceblue");
//Save and Launch
document.SaveToFile("Encryption.docx", FileFormat.Docx);
System.Diagnostics.Process.Start("Encryption.docx");
}
}
}
Imports Spire.Doc
Namespace Encryption
Friend Class Program
Shared Sub Main(ByVal args() As String)
'Load Document
Dim document As New Document()
document.LoadFromFile("E:\Work\Documents\WordDocuments\Spire.Doc for .NET.docx")
'Encrypt
document.Encrypt("eiceblue")
'Save and Launch
document.SaveToFile("Encryption.docx", FileFormat.Docx)
System.Diagnostics.Process.Start("Encryption.docx")
End Sub
End Class
End Namespace
Spire.Doc, an easy-to-use component to operate Word document, allows developers to fast generate, write, edit and save Word (Word 97-2003, Word 2007, Word 2010) in C# and VB.NET for .NET, Silverlight and WPF.
C#/VB.NET: Add or Remove Cell Borders in Excel
Cell borders refer to lines that can be added around a cell or range of cells. They can be used to serve different purposes, such as to separate sections in a worksheet, draw readers' attention to important cells, or make the worksheet look more presentable. This article will introduce how to add or remove cell borders in Excel in C# and VB.NET using Spire.XLS for .NET.
Install Spire.XLS for .NET
To begin with, you need to add the DLL files included in the Spire.XLS 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.XLS
Add Cell Borders in Excel in C# and VB.NET
Spire.XLS for .NET allows adding various kinds of borders to cells in Excel, such as left border, right border, top border, bottom border, diagonal borders, inside borders and outside borders.
You can add a specific border or multiple borders to individual cells or ranges of cells. In addition, you can also set different line styles and line colors for the borders. The following are the main steps to apply different kinds of cell borders with different line styles and line colors:
- Initialize an instance of the Workbook class.
- Get a specific worksheet by its index through Workbook.Worksheets[int] property.
- Get a specific cell range by its name through Worksheet.Range[string] property.
- Get specific borders (such as left, right, top, bottom and diagonal) from the Borders collection of the cell range through CellRange.Borders[BordersLineType] property.
- Set the line styles of the specific borders through IBorder.LineStyle property.
- Set the line colors of the specific borders through IBorder.Color property.
- Get a specific cell range by its name through Worksheet.Range[string] property.
- Add outside borders and/or inside borders to the cell range using CellRange.BorderAround(LineStyleType, Color) method and/or CellRange.BorderInside(LineStyleType, Color) method. Note that inside borders cannot be applied to a single cell.
- Get a specific cell range by its name through Worksheet.Range[string] property.
- Set the line styles and line colors for borders of the cell range through BordersCollection.LineStyle and BordersCollection.Color properties, then set the line style and color for diagonal borders of the cell range.
- Save the result file using Workbook.SaveToFile() method.
- C#
- VB.NET
using Spire.Xls;
using Spire.Xls.Core;
using System.Drawing;
namespace AddCellBorders
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook instance
Workbook workbook = new Workbook();
//Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
//Set left, right, top, bottom and diagonal up borders for cell B2
CellRange range = sheet.Range["B2"];
IBorder leftBorder = range.Borders[BordersLineType.EdgeLeft];
leftBorder.LineStyle = LineStyleType.MediumDashDotDot;
leftBorder.Color = Color.Red;
IBorder rightBorder = range.Borders[BordersLineType.EdgeRight];
rightBorder.LineStyle = LineStyleType.MediumDashed;
rightBorder.Color = Color.Red;
IBorder topBorder = range.Borders[BordersLineType.EdgeTop];
topBorder.LineStyle = LineStyleType.Medium;
topBorder.Color = Color.Red;
IBorder bottomBorder = range.Borders[BordersLineType.EdgeBottom];
bottomBorder.LineStyle = LineStyleType.Medium;
bottomBorder.Color = Color.Red;
IBorder diagonalUpBorder = range.Borders[BordersLineType.DiagonalUp];
diagonalUpBorder.LineStyle = LineStyleType.Thin;
diagonalUpBorder.Color = Color.Red;
//Set diagonal borders for cell C4
range = sheet.Range["C4"];
diagonalUpBorder = range.Borders[BordersLineType.DiagonalUp];
diagonalUpBorder.LineStyle = LineStyleType.Double;
diagonalUpBorder.Color = Color.Blue;
IBorder diagonalDownBorder = range.Borders[BordersLineType.DiagonalDown];
diagonalDownBorder.LineStyle = LineStyleType.Double;
diagonalDownBorder.Color = Color.Blue;
//Set outside borders for cell D6
range = sheet.Range["D6"];
range.BorderAround(LineStyleType.Double, Color.Green);
//Set inside borders for cell range E8:F10
range = sheet.Range["E8:F10"];
range.BorderInside(LineStyleType.MediumDashed, Color.DarkGray);
//Set inside and outside borders for cell range F12:G14
range = sheet.Range["F12:G14"];
range.BorderInside(LineStyleType.MediumDashed, Color.Pink);
range.BorderAround(LineStyleType.Medium, Color.Magenta);
//Set borders for cell range G16:H18
range = sheet.Range["G16:H18"];
range.Borders.LineStyle = LineStyleType.Thick;
range.Borders.Color = Color.Cyan;
//Set line style and line color of diagonal borders for cell range G16:H18
diagonalUpBorder = range.Borders[BordersLineType.DiagonalUp];
diagonalUpBorder.LineStyle = LineStyleType.Dotted;
diagonalUpBorder.Color = Color.DarkGray;
diagonalDownBorder = range.Borders[BordersLineType.DiagonalDown];
diagonalDownBorder.LineStyle = LineStyleType.Dotted;
diagonalDownBorder.Color = Color.DarkGray;
//Save the result file
workbook.SaveToFile("AddBorders.xlsx", ExcelVersion.Version2013);
}
}
}

Remove Cell Borders in Excel in C# and VB.NET
You can remove all borders of a cell or range of cells by setting the CellRange.Borders.LineStyle property as LineStyleType.None. The following are the details steps:
- Initialize an instance of the Workbook class.
- Load an Excel file using Workbook.LoadFromFile() method.
- Get a specific worksheet by its index through Workbook.Worksheets[int] property.
- Get a specific cell range by its name through Worksheet.Range[string] property.
- Remove the borders of the cell range by setting CellRange.Borders.LineStyle property as LineStyleType.None.
- Save the result file using Workbook.SaveToFile() method.
- C#
- VB.NET
using Spire.Xls;
namespace RemoveCellBorders
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load an Excel file
workbook.LoadFromFile("AddBorders.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
//Remove borders of cell range G16:H18
CellRange range = sheet.Range["G16:H18"];
range.Borders.LineStyle = LineStyleType.None;
workbook.SaveToFile("RemoveBorders.xlsx", ExcelVersion.Version2013);
}
}
}

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.