C# Regex Replace: Replace Text in Word Document [Tutorial]

When working with Word templates, it's common to replace specific placeholders with real content—like names, dates, or even company logos. Manually updating each instance may take lots of effort and time. Fortunately, you can automate this process using code. In this tutorial, we'll show you how to use C# regex replace to find and replace text in Word documents. You'll learn how to apply regular expressions across the entire document, target specific paragraphs, and even replace matched text with images.
- Before We Start: Install Word Library
- Replace Text in an Entire Word Document
- Replace Text within Specific Paragraph in C#
- Replace Regex Matches with Images
- Replace Text with Regex in VB.NET
- Conclusion
Before We Start: Install Word Library
To make this task easier, we recommend using Spire.Doc for .NET — a powerful Word library designed to automate common document operations such as reading, editing, and converting Word files. With Spire.Doc, performing a C# regex replace in Word documents can be done in just a few lines of code.
You can install the library via NuGet with the following command:
PM> Install-Package Spire.Doc
Alternatively, you can download the Spire.Doc package and install it with custom settings. A free version is also available, ideal for small projects or evaluation purposes.
Use Regex to Replace Text in an Entire Word Document
Let's start with the most common scenario — replacing text throughout the entire Word document. You can use regular expressions to match all patterns like #name or #tel, then replace them with actual values such as a person's name or phone number.
With the help of the Document.Replace() method provided by Spire.Doc, this task becomes incredibly simple. Here's a step-by-step explanation along with sample code to show how to replace text using regex in C#.
Code example - replacing #name with "May" in the entire Word document using C#:
using Spire.Doc;
using System.Text.RegularExpressions;
namespace FindText
{
class Program
{
static void Main(string[] args)
{
// Create an object of Document class and load a Word document
Document doc = new Document();
doc.LoadFromFile("/input/replace template.docx");
// Set the regular expression
Regex regex = new Regex(@"#\w+\b");
// Replace all matches with "May"
doc.Replace(regex, "May");
// Save the document
doc.SaveToFile("/output/replacealloccurences.docx", FileFormat.Docx2013);
}
}
}
Here is a comparison preview of the results before and after using regex to replace text in C#: 
Steps Explained:
- Create a Document instance and load a Word document from files.
- Set the regular expression.
- Replace all matches in the document with Documet.Replace() method.
- Save the updated document.
Apply Regex Replace to a Specific Paragraph in C#
Replacing text across the entire document may seem straightforward, but how can we achieve the same result within a specific paragraph? When you need more precise control, such as performing regex replace only within a paragraph range, you can retrieve the paragraph text and reset its content manually. In code, this means using regular expressions to locate matches within the target paragraph, remove the original text, and insert the replacement.
Let’s first look at a real-world code example — we’ll break down the detailed steps right after.
Code example - replacing #name with "Lily" in the first paragraph using regular expression:
using Spire.Doc;
using Spire.Doc.Documents;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
// Create a Document object and load a template
Document doc = new Document();
doc.LoadFromFile("/input/replace template.docx");
Regex regex = new Regex(@"#\w+\b");
// Get the first paragraph
Paragraph para = doc.Sections[0].Paragraphs[0];
string originalText = para.Text;
if (regex.IsMatch(originalText))
{
string newText = regex.Replace(originalText, "Lily");
// Clear the content and append the new text
para.ChildObjects.Clear();
para.AppendText(newText);
}
// Save the updated document
doc.SaveToFile("/output/replacefirstpara.docx", FileFormat.Docx2013);
}
}
Here is a before-and-after comparison of using regular expressions in C# to replace text in the first paragraph: 
Detailed steps explained:
- Create a Document object and load the Word file.
- Access the target paragraph using Sections[].Paragraphs[] property.
- Get the original text from the paragraph.
- Use a regular expression to find and replace matching text.
- Clear the original content and append the updated text to the paragraph.
- Save the modified document.
Replace Regex Matches with Images in Word Using C#
Now that we’ve covered how to replace text in the entire document or within a single paragraph, let’s move on to something more advanced—replacing text with images. This is often used in practical scenarios like generating reports or company brochures. For instance, you might want to replace a placeholder such as [logo] with your company’s actual logo.
With the help of C# regex replace and Spire.Doc’s image insertion APIs, this task can also be automated. Let’s take a look at a real code example first, then we’ll explain how it works.
Code example – replacing [avatar] with an image:
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Text.RegularExpressions;
namespace RegexReplaceWithImage
{
class Program
{
static void Main(string[] args)
{
// Create a Document object and load a Word file from disk
Document document = new Document();
document.LoadFromFile(@"\input\replace template.docx");
// Define a regular expression to match placeholders
Regex regex = new Regex(@"\[\w+\]", RegexOptions.IgnoreCase);
// Find all matches in the document that match the pattern
TextSelection[] selections = document.FindAllPattern(regex);
// Loop through each matched placeholder
foreach (TextSelection selection in selections)
{
// Create a picture object and load the image from disk
DocPicture pic = new DocPicture(document);
pic.LoadImage(@"\avatar-1.png");
// Get the matched text as a single text range
TextRange textRange = selection.GetAsOneRange();
// Get the index of the text range in its parent paragraph
int index = textRange.OwnerParagraph.ChildObjects.IndexOf(textRange);
// Insert the image at the matched position
textRange.OwnerParagraph.ChildObjects.Insert(index, pic);
// Remove the original placeholder text
textRange.OwnerParagraph.ChildObjects.Remove(textRange);
}
// Save the modified document to disk
document.SaveToFile(@"\output\ReplaceTextWithImage.docx", FileFormat.Docx2016);
document.Close();
}
}
}
Here is a before-and-after comparison of replacing text with an image using regex in C#: 
Detailed steps explained:
- Create an object of Document class and read a Word document.
- Define a regular expression to match target content.
- Find all occurrences using Document.FindAllPattern() method.
- Loop through the collection of matches.
- Create a DocPicture instance and load an image.
- Get the matched text as a text range and retrieve its index in the parent paragraph.
- Insert the image at the position and remove the original text.
- Save the Word document as a new file.
Replace Text with Regex in VB.NET
If you're working with VB.NET instead of C#, you can achieve the same result using regular expressions to search and replace text throughout a Word document. The approach is similar—load the file, apply a regex pattern, and update the content. Here's a simple example to get you started.
Imports Spire.Doc
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim doc As New Document()
doc.LoadFromFile("/input/replace template.docx")
Dim regex As New Regex("#\w+\b")
doc.Replace(regex, "Lena")
doc.SaveToFile("/output/regexreplace.docx", FileFormat.Docx2013)
End Sub
End Module
Above is the VB.NET code for replacing text throughout an entire Word document using regular expressions.
If you need to perform other tasks, such as replacing text in specific paragraphs or replacing text with images, you can easily convert the C# code examples into VB.NET using the C# Code ⇆ VB.NET Code Converter — a handy tool developed by the Spire.Doc team.
The Conclusion
With the help of regular expressions, replacing text or even inserting images in Word documents using C# becomes a smooth and efficient process. Whether you're working on templates, reports, or personalized documents, this approach saves time and reduces manual work. Ready to try it out? Download Spire.Doc and get started with a free 30-day trial license—perfect for evaluation and small projects.
How to set word bullet style by appending the HTML code in C#
With the help of Spire.Doc for .NET, developers can easily set bullet style for the existing word documents via invoke p.ListFormat.ApplyBulletStyle() method to format. This article will show you how to convert HTML list into word and set the bullet style for the word list in C#.
Firstly, please view the effective screenshot for the result word document:

Here comes to the steps:
Step 1: Create a new document and add a section to the document.
Document document = new Document(); Section section=document.AddSection();
Step 2: Add word list to the paragraph by appending HTML.
Paragraph paragraph = section.AddParagraph();
paragraph.AppendHTML("<ol><li>Version 1</li><li>Version 2</li><li>Version 3</li></ol>");
Step 3: Set the bullet style for the paragraph.
foreach (Paragraph p in section.Paragraphs)
{
p.ApplyStyle(BuiltinStyle.Heading2);
if (p.ListFormat.CurrentListLevel != null)
{
p.ListFormat.ApplyBulletStyle();
}
}
Step 4: Save the document to file
document.SaveToFile("result.docx",FileFormat.Docx);
Full codes:
// Create a new Word document object
Document document = new Document();
// Add a section to the document
Section section = document.AddSection();
// Add a paragraph to the section
Paragraph paragraph = section.AddParagraph();
// Append HTML content to the paragraph
paragraph.AppendHTML("- Version 1
- Version 2
- Version 3
");
// Loop through all paragraphs in the section
foreach (Paragraph p in section.Paragraphs)
{
// Apply "Heading 2" built-in style to the paragraph
p.ApplyStyle(BuiltinStyle.Heading2);
// Check if the paragraph has listformat
if (p.ListFormat.CurrentListLevel != null)
{
// Apply bullet style
p.ListFormat.ApplyBulletStyle();
}
}
// Save the document to a file in DOCX format
document.SaveToFile("result.docx", FileFormat.Docx);
// Dispose
document.Dispose();
How to Merge and Center Cells in Excel using C# (and VB.NET)

Working with large Excel files often means merging rows, columns, or specific cell ranges to keep the data clean and easy to read. You can merge cells in Excel using C# or VB.NET with just a few lines of code and even center the content both horizontally and vertically for a professional look. Whether it’s combining entire rows, joining columns, or formatting a selected range, these examples show how to automate the process and improve your workflow.
- Merge Rows or Columns in Excel using C#
- Merge a Specific Cell Range in Excel
- Merge and Center Cells in Excel using VB.NET
- The Conclusion
If you often work with Excel files in .NET projects, handling tasks like merging cells, formatting data, or generating reports, you’ll want a tool that makes the process fast and reliable. Spire.XLS is a lightweight library that lets you create, read, and modify Excel files directly in C# or VB.NET—without relying on Microsoft Office. You can add it to your project in seconds via NuGet:
PM> Install-Package Spire.XLS
From there, you’re ready to start automating your Excel workflow.
Merge Rows or Columns in Excel using C#
Merging rows or columns in Excel is a common way to organize data and create professional-looking spreadsheets. For example, you can merge the first row across multiple columns to form a clear, centered table header. Using C# code, this process can be automated easily, saving time and ensuring consistency across large Excel files.
Here's the code example of merging the first row and centering it in Excel using C#:
using Spire.Xls;
namespace MergeCells
{
class Program
{
static void Main(string[] args)
{
// Create a Workbook instance and load an Excel file
Workbook workbook = new Workbook();
workbook.LoadFromFile("\\Population.xlsx");
// Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
// Merge the first row
sheet.Rows[0].Merge();
// Merge the first column
//sheet.Columns[0].Merge();
// Set the alignment to center horizontally and vertically
sheet.Rows[0].Style.HorizontalAlignment = HorizontalAlignType.Center;
sheet.Rows[0].Style.VerticalAlignment = VerticalAlignType.Center;
// Save the Excel file
workbook.SaveToFile("\\Mergerowsandcenter.xls");
}
}
}
Here's the preview of merging the first row in Excel:

Code steps explained:
- Create a Workbook object and read an Excel file.
- Get a worksheet.
- Merge a certain row using Worksheet.Rows[].Merge() method.
- Set the alignment to center horizontally and vertically by adjusting the Style.HorizontalAlignment and Style.VerticalAlignment properties.
- Save the modified Excel file.
The C# code above for merging rows in an Excel file can also be used to merge columns, which is indicated with comments in the code.
After merging cells to create a clean table header, you might sometimes need to undo the operation. You can easily unmerge cells in Excel in C# or VB.NET, restoring the original cell layout without affecting your data.
Merge a Specific Cell Range in Excel
Merging a specific cell range in Excel using C# is useful when you want to highlight a section of data, such as a summary row or a group of related columns. The process is very similar to merging entire rows or columns, and you can use the same Merge() method—applied to a CellRange object via Worksheet.Range[].Merge() method. By specifying the exact range to merge, you can create a clear, organized layout that improves readability and automates the operation across multiple sheets or files without manually adjusting each cell.
The code example below demonstrates how to merge the cell range "B6:E6" in an Excel worksheet using C#:
using Spire.Xls;
namespace MergeCells
{
class Program
{
static void Main(string[] args)
{
// Create a Workbook instance and load an Excel file
Workbook workbook = new Workbook();
workbook.LoadFromFile("\\Population.xlsx");
// Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
// Merge the particular cell range in Excel
sheet.Range["B6:E6"].Merge();
// Save the Excel file
workbook.SaveToFile("\\Mergecellrange.xls");
}
}
}
Here's the preview of merging a cell range in an Excel file using C#:

Merge and Center Cells in Excel using VB.NET
Just like in C#, you can merge and center cells in Excel using VB.NET to create clean table headers or highlight key data sections. The steps are very similar, and the same Merge() method applies to rows, columns, or specific cell ranges. If you want, you can even convert C# examples to VB.NET using our handy C# ↔ VB.NET code converter, making it easy to adapt existing code for your project.
Here's a code example of merging the first row and centering it in Excel using VB.NET:
Imports Spire.Xls
Namespace MergeCells
Friend Class Program
Private Shared Sub Main(args As String())
' Create a Workbook instance and load an Excel file
Dim workbook As Workbook = New Workbook()
workbook.LoadFromFile("E:\Administrator\Python1\input\Population.xlsx")
' Get the first worksheet
Dim sheet As Worksheet = workbook.Worksheets(0)
' Merge the first row
sheet.Rows(0).Merge()
' Merge the first column
'sheet.Columns[0].Merge();
' Set the alignment to center horizontally and vertically
sheet.Rows(0).Style.HorizontalAlignment = HorizontalAlignType.Center
sheet.Rows(0).Style.VerticalAlignment = VerticalAlignType.Center
' Save the Excel file
workbook.SaveToFile("\Mergerowsandcenter.xls")
End Sub
End Class
End Namespace
The Conclusion
By following these examples, you can merge cells in Excel using C#, whether it’s entire rows, columns, or specific ranges. With the help of Spire.XLS, you can merge cells in Excel files automatically without hassle and create clear, professional-looking spreadsheets. Start streamlining your workflow today and get a 30-day free license to try all features without restrictions.
Convert Excel to DataTable in C#: Worksheets, Ranges & Beyond

Working with Excel data is a common requirement in .NET development. Developers often need to convert Excel files into a DataTable, which provides a structured way to manipulate data, perform LINQ queries, bind to UI controls, or import into a database.
Although this task is common, the implementation details are not always straightforward. Converting Excel data into a DataTable in C# can be achieved in several ways, but traditional approaches often depend on OLEDB drivers or involve lengthy OpenXML programming, both of which add unnecessary complexity and external dependencies. In this guide, we’ll use Spire.XLS for .NET to simplify the process of importing Excel data into a DataTable with C# code. The library provides built-in methods to load Excel files, export worksheets or specific ranges, and work with the data directly in a DataTable.
Quick Navigation
- What is a DataTable and Why Use It?
- Preparing the Environment
- Converting Excel to DataTable in C#
- Bonus: Exporting DataTable Back to Excel
- Handling Large Excel Files and Performance Tips
- Best Practices
- Conclusion
- FAQ
What is a DataTable and Why Use It?
A DataTable in C# is a memory-resident representation of structured data. It allows developers to:
- Store Excel data in tabular form.
- Perform filtering, sorting, and LINQ queries.
- Bind to UI components like DataGridView.
- Bulk insert into relational databases.
Compared with DataSet, a DataTable is lightweight and especially well-suited for working with a single worksheet or range of data.
Preparing the Environment
Before starting, install Spire.XLS for .NET in your project. The easiest way is through NuGet:
Install-Package Spire.XLS
Then, import the required namespaces in your C# code:
using Spire.Xls;
using System.Data;
Converting Excel to DataTable in C#
The following sections demonstrate how to load an Excel file and convert its contents into a DataTable using Spire.XLS. Unlike older methods that depend on OLEDB, this library works without Microsoft Office installation, making it reliable for both desktop and server-side applications.
Load an Excel File
Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");
This creates a Workbook object from the specified Excel file, which you can then use to access individual worksheets.
Convert a Worksheet to DataTable
Worksheet sheet = workbook.Worksheets[0];
DataTable dataTable = sheet.ExportDataTable(sheet.AllocatedRange, true);
Here, the entire first worksheet is exported to a DataTable.
- sheet.AllocatedRange retrieves the used range of the worksheet.
- The true parameter means the first row will be treated as column headers.
This approach is useful when you want to import all data from a sheet directly into a DataTable, for example when binding to a DataGridView or performing bulk inserts into a database.
Convert a Specific Range to DataTable
DataTable partialTable = sheet.ExportDataTable(sheet.Range["A1:C10"], true);
This snippet converts only the range A1:C10 into a DataTable. It’s a practical choice when dealing with large Excel files, where only part of the sheet is needed for processing, or when extracting a specific report section.
Complete Example: Excel Worksheet to DataTable with C#
The following example demonstrates the entire workflow of loading an Excel file and converting it into a DataTable. After running this code, you can process the table further, such as querying, filtering, or inserting into a database.
using Spire.Xls;
using System.Data;
class Program
{
static void Main()
{
// Load Excel file
Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");
// Convert first worksheet to DataTable
Worksheet sheet = workbook.Worksheets[0];
DataTable dataTable = sheet.ExportDataTable(sheet.AllocatedRange, true);
// Print row count
Console.WriteLine("Rows imported: " + dataTable.Rows.Count);
// Print column names
foreach (DataColumn col in dataTable.Columns)
{
Console.Write(col.ColumnName + "\t");
}
Console.WriteLine();
// Print all rows
foreach (DataRow row in dataTable.Rows)
{
foreach (var item in row.ItemArray)
{
Console.Write(item + "\t");
}
Console.WriteLine();
}
}
}
This code loads the first worksheet from an Excel file, exports its content into a DataTable, and prints the table to the console. The following screenshot shows an example of the output:

For scenarios where you need to read Excel data cell by cell, see our guide on reading Excel files in C#.
Bonus: Exporting DataTable Back to Excel in C#
In some cases, you may also need to write modified data from a DataTable back to Excel. This can be done easily:
Workbook wb = new Workbook();
Worksheet ws = wb.Worksheets[0];
// Assume dataTable is already populated
ws.InsertDataTable(dataTable, true, 1, 1);
wb.SaveToFile("Output.xlsx", ExcelVersion.Version2016);
This code inserts the DataTable starting at cell A1 and saves the file. It demonstrates the reverse workflow, ensuring smooth two-way data exchange between Excel and C#. For more details, you can check How to Export DataTable into Excel in C#.
Handling Large Excel Files and Performance Tips
When working with large Excel files, performance optimization is key. Here are a few best practices:
- Read only the required worksheets instead of loading all.
- Export specific ranges rather than entire sheets if possible.
- Use stream-based methods (LoadFromStream) to avoid file locks.
- Minimize memory usage by processing rows iteratively when handling very large DataTables.
Spire.XLS supports .xls, .xlsx, and .csv formats consistently, making it suitable across different scenarios.
Best Practices
When converting Excel to DataTable, keep in mind:
- Data type handling: Excel stores values as text by default. Convert them to int, decimal, or DateTime as needed.
- Null or empty cells: Always check for missing values to prevent runtime errors.
- Database integration: Before bulk inserting into SQL Server or another database, validate and sanitize the DataTable.
Conclusion
Converting Excel data into a DataTable is a common but critical task in .NET development. With Spire.XLS for .NET, you can achieve this efficiently without relying on OLEDB drivers or complex OpenXML parsing.
Whether you need to convert an entire worksheet, extract a specific range, or write data back to Excel, the process remains straightforward and reliable. Mastering this workflow ensures smoother integration between Excel data and your C# applications.
If you want to unlock the full feature set of Spire.XLS, you can apply for a free temporary license. For smaller projects, you can also use Free Spire.XLS for .NET.
FAQ
Q: How do I import data from Excel to DataTable in C#?
Use Worksheet.ExportDataTable() to directly convert worksheet data into a DataTable.
Q: Can I read Excel into DataTable without OLEDB?
Yes. Spire.XLS does not require OLEDB or Microsoft Office installation.
Q: How to read only a specific worksheet or range into a DataTable?
Pass the target Worksheet or Range to ExportDataTable().
Q: Can I export a DataTable back to Excel in C#?
Yes. Use Worksheet.InsertDataTable() and then save the file with SaveToFile().