How To Generate A Word Document In C#

Generating Word documents is a common task in many C# applications. This tutorial will guide you through the process of generating and working with Word documents using C#. We'll cover how to create Word documents, manipulate existing MS Word documents, and utilize various features of the Microsoft Word application.

Manipulating Word documents in C# requires understanding the Microsoft Office Interop Word library. This library allows you to interact with Microsoft Word, creating, reading, and editing Word documents programmatically. Let's get started!

How To Generate Word Document In C#

  1. Create a new C# project in Visual Studio
  2. Add a reference to the C# Word library3. Initialize the Word application
  3. Add some paragraphs and tables in the Word document5. Save the document and close the Word app

Prerequisites

Before starting with the C# code to create and manipulate MS Word documents, ensure you have the following setup

Microsoft Word Installation

Make sure Microsoft Word is installed on your system, as it's essential for the tasks we'll perform. You can install it from the official Microsoft website or your computer's app store.

Visual Studio Setup

Visual Studio is required for this project. If you don’t have it, download and install Visual Studio Community from the Microsoft website. Ensure it's set up to create a Console Application.

Setting Up the Environment

Step 1 Creating a New Project

In Visual Studio, create a new C# project. You can choose a Console App for simplicity.

How To Generate A Word Document In C#: Figure 1

How To Generate A Word Document In C#: Figure 2

Step 2 Adding References

  1. Right-click on your project in Solution Explorer.
  2. Select "Manage NuGet Packages."
  3. Search for "Microsoft.Office.Interop.Word" and install it.

How To Generate A Word Document In C#: Figure 3

This package is essential for interacting with MS Word.

Creating a New Word Document

Step 1 Initializing the Word Application

using Word = Microsoft.Office.Interop.Word;
class Program
{
    static void Main(string[] args)
    {
        var wordApp = new Word.Application();
        wordApp.Visible = true;
    }
}
using Word = Microsoft.Office.Interop.Word;
class Program
{
    static void Main(string[] args)
    {
        var wordApp = new Word.Application();
        wordApp.Visible = true;
    }
}
Imports Word = Microsoft.Office.Interop.Word
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim wordApp = New Word.Application()
		wordApp.Visible = True
	End Sub
End Class
VB   C#

This code initializes the Word application, allowing you to manipulate Word documents.

Step 2 Adding a Document

Word.Document newDoc = wordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);
Word.Document newDoc = wordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);
Dim newDoc As Word.Document = wordApp.Documents.Add(missing, missing, missing, missing)
VB   C#

Here, a new Word document is created. The missing variable represents the missing value object, used when optional arguments are not specified.

Manipulating the Document

Adding Text

To insert text into the Word document, you need to create a paragraph object and then set its text.

// Create a new paragraph at the end of the document
Word.Paragraph para = newDoc.Content.Paragraphs.Add(ref missing);
// Set the text for the new paragraph
para.Range.Text = "This is a sample paragraph in the Word document";
// Additional formatting options for the paragraph
para.Range.Font.Name = "Arial"; // Set font to Arial
para.Range.Font.Size = 12; // Set font size to 12
para.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft; // Align text to left
para.SpaceAfter = 10; // Add space after paragraph
para.Range.InsertParagraphAfter(); // Insert a new paragraph after the current one
// Create a new paragraph at the end of the document
Word.Paragraph para = newDoc.Content.Paragraphs.Add(ref missing);
// Set the text for the new paragraph
para.Range.Text = "This is a sample paragraph in the Word document";
// Additional formatting options for the paragraph
para.Range.Font.Name = "Arial"; // Set font to Arial
para.Range.Font.Size = 12; // Set font size to 12
para.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft; // Align text to left
para.SpaceAfter = 10; // Add space after paragraph
para.Range.InsertParagraphAfter(); // Insert a new paragraph after the current one
' Create a new paragraph at the end of the document
Dim para As Word.Paragraph = newDoc.Content.Paragraphs.Add(missing)
' Set the text for the new paragraph
para.Range.Text = "This is a sample paragraph in the Word document"
' Additional formatting options for the paragraph
para.Range.Font.Name = "Arial" ' Set font to Arial
para.Range.Font.Size = 12 ' Set font size to 12
para.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft ' Align text to left
para.SpaceAfter = 10 ' Add space after paragraph
para.Range.InsertParagraphAfter() ' Insert a new paragraph after the current one
VB   C#

In this code, a new paragraph is added to the end of the document's content. The text of the paragraph is set to a sample text. Additionally, the font is changed to Arial with a size of 12, and the paragraph is aligned to the left.

Space is added after the paragraph for better readability, and a new paragraph is inserted afterward, which allows for further content to be added in a structured manner. This method of adding and formatting text is a key part of creating Word documents programmatically, as it lays the foundation for more complex document structures.

This snippet adds a new paragraph with some text.

Inserting a Table

Word.Table newTable;
Word.Range tableRange = para.Range;
newTable = newDoc.Tables.Add(tableRange, 3, 2, ref missing, ref missing);
newTable.Borders.Enable = 1;
foreach (Word.Row row in newTable.Rows)
{
    foreach (Word.Cell cell in row.Cells)
    {
        // Header cells
        if (cell.RowIndex == 1)
            cell.Range.Text = "Header " + cell.ColumnIndex.ToString();
        // Data cells
        else
            cell.Range.Text = "Row " + cell.RowIndex + ", Column " + cell.ColumnIndex;
    }
}
Word.Table newTable;
Word.Range tableRange = para.Range;
newTable = newDoc.Tables.Add(tableRange, 3, 2, ref missing, ref missing);
newTable.Borders.Enable = 1;
foreach (Word.Row row in newTable.Rows)
{
    foreach (Word.Cell cell in row.Cells)
    {
        // Header cells
        if (cell.RowIndex == 1)
            cell.Range.Text = "Header " + cell.ColumnIndex.ToString();
        // Data cells
        else
            cell.Range.Text = "Row " + cell.RowIndex + ", Column " + cell.ColumnIndex;
    }
}
Dim newTable As Word.Table
Dim tableRange As Word.Range = para.Range
newTable = newDoc.Tables.Add(tableRange, 3, 2, missing, missing)
newTable.Borders.Enable = 1
For Each row As Word.Row In newTable.Rows
	For Each cell As Word.Cell In row.Cells
		' Header cells
		If cell.RowIndex = 1 Then
			cell.Range.Text = "Header " & cell.ColumnIndex.ToString()
		' Data cells
		Else
			cell.Range.Text = "Row " & cell.RowIndex & ", Column " & cell.ColumnIndex
		End If
	Next cell
Next row
VB   C#

This code sets up the table with bold headers and distinguishes them from the data cells using formatting. The headers are given a background color for emphasis. Each cell in the table is populated with text indicating its position, which is particularly useful for understanding how the table is structured in the code. This level of customization provides clarity and enhances the overall presentation of the table in the document.

Saving and Closing the Document

object filename = @"C:\YourPath\NewWordDoc.docx";
newDoc.SaveAs2(ref filename);
newDoc.Close(ref missing, ref missing, ref missing);
wordApp.Quit(ref missing, ref missing, ref missing);
object filename = @"C:\YourPath\NewWordDoc.docx";
newDoc.SaveAs2(ref filename);
newDoc.Close(ref missing, ref missing, ref missing);
wordApp.Quit(ref missing, ref missing, ref missing);
Dim filename As Object = "C:\YourPath\NewWordDoc.docx"
newDoc.SaveAs2(filename)
newDoc.Close(missing, missing, missing)
wordApp.Quit(missing, missing, missing)
VB   C#

This finalizes the document, saving it to a specified path. It'll create Word document to the specified path. Existing Word document is an important step that we achieved by using the Close method.

Handling Exceptions

Always include exception handling to catch any errors that might occur during the process.

try
{
    // Your code here
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}
finally
{
    // Cleanup resources
}
try
{
    // Your code here
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}
finally
{
    // Cleanup resources
}
Try
	' Your code here
Catch ex As Exception
	Console.WriteLine(ex.Message)
Finally
	' Cleanup resources
End Try
VB   C#

Complete Code

Here is the complete code which you can use in your C# application.

using System;
using Word = Microsoft.Office.Interop.Word;
class Program
{
    static void Main(string[] args)
    {
        // Initialize Word application
        Word.Application wordApp = new Word.Application();
        wordApp.Visible = true;
        // Add a new document
        Word.Document newDoc = wordApp.Documents.Add();
        // Add a paragraph with some text
        Word.Paragraph para = newDoc.Content.Paragraphs.Add();
        para.Range.Text = "This is a sample paragraph in the Word document";
        para.Range.Font.Name = "Arial";
        para.Range.Font.Size = 12;
        para.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
        para.SpaceAfter = 10;
        para.Range.InsertParagraphAfter();
        // Add a table after the paragraph
        Word.Range tableRange = para.Range;
        Word.Table newTable = newDoc.Tables.Add(tableRange, 3, 2);
        newTable.Borders.Enable = 1;
        foreach (Word.Row row in newTable.Rows)
        {
            foreach (Word.Cell cell in row.Cells)
            {
                if (cell.RowIndex == 1)
                {
                    cell.Range.Text = "Header " + cell.ColumnIndex.ToString();
                    cell.Range.Font.Bold = 1;
                    cell.Shading.BackgroundPatternColor = Word.WdColor.wdColorGray25;
                }
                else
                {
                    cell.Range.Text = "Data " + cell.RowIndex + ", " + cell.ColumnIndex;
                    cell.Range.Font.Bold = 0;
                }
            }
        }
        // Save the document
        object fileName = @"C:\NewWordDoc.docx";
        newDoc.SaveAs2(ref fileName);
        // Close the document and Word application
        newDoc.Close();
        wordApp.Quit();
    }
}
using System;
using Word = Microsoft.Office.Interop.Word;
class Program
{
    static void Main(string[] args)
    {
        // Initialize Word application
        Word.Application wordApp = new Word.Application();
        wordApp.Visible = true;
        // Add a new document
        Word.Document newDoc = wordApp.Documents.Add();
        // Add a paragraph with some text
        Word.Paragraph para = newDoc.Content.Paragraphs.Add();
        para.Range.Text = "This is a sample paragraph in the Word document";
        para.Range.Font.Name = "Arial";
        para.Range.Font.Size = 12;
        para.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
        para.SpaceAfter = 10;
        para.Range.InsertParagraphAfter();
        // Add a table after the paragraph
        Word.Range tableRange = para.Range;
        Word.Table newTable = newDoc.Tables.Add(tableRange, 3, 2);
        newTable.Borders.Enable = 1;
        foreach (Word.Row row in newTable.Rows)
        {
            foreach (Word.Cell cell in row.Cells)
            {
                if (cell.RowIndex == 1)
                {
                    cell.Range.Text = "Header " + cell.ColumnIndex.ToString();
                    cell.Range.Font.Bold = 1;
                    cell.Shading.BackgroundPatternColor = Word.WdColor.wdColorGray25;
                }
                else
                {
                    cell.Range.Text = "Data " + cell.RowIndex + ", " + cell.ColumnIndex;
                    cell.Range.Font.Bold = 0;
                }
            }
        }
        // Save the document
        object fileName = @"C:\NewWordDoc.docx";
        newDoc.SaveAs2(ref fileName);
        // Close the document and Word application
        newDoc.Close();
        wordApp.Quit();
    }
}
Imports System
Imports Word = Microsoft.Office.Interop.Word
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Initialize Word application
		Dim wordApp As New Word.Application()
		wordApp.Visible = True
		' Add a new document
		Dim newDoc As Word.Document = wordApp.Documents.Add()
		' Add a paragraph with some text
		Dim para As Word.Paragraph = newDoc.Content.Paragraphs.Add()
		para.Range.Text = "This is a sample paragraph in the Word document"
		para.Range.Font.Name = "Arial"
		para.Range.Font.Size = 12
		para.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft
		para.SpaceAfter = 10
		para.Range.InsertParagraphAfter()
		' Add a table after the paragraph
		Dim tableRange As Word.Range = para.Range
		Dim newTable As Word.Table = newDoc.Tables.Add(tableRange, 3, 2)
		newTable.Borders.Enable = 1
		For Each row As Word.Row In newTable.Rows
			For Each cell As Word.Cell In row.Cells
				If cell.RowIndex = 1 Then
					cell.Range.Text = "Header " & cell.ColumnIndex.ToString()
					cell.Range.Font.Bold = 1
					cell.Shading.BackgroundPatternColor = Word.WdColor.wdColorGray25
				Else
					cell.Range.Text = "Data " & cell.RowIndex & ", " & cell.ColumnIndex
					cell.Range.Font.Bold = 0
				End If
			Next cell
		Next row
		' Save the document
		Dim fileName As Object = "C:\NewWordDoc.docx"
		newDoc.SaveAs2(fileName)
		' Close the document and Word application
		newDoc.Close()
		wordApp.Quit()
	End Sub
End Class
VB   C#

Here you can see that the document created successfully.

How To Generate A Word Document In C#: Figure 4

Introduction to IronXL

How To Generate A Word Document In C#: Figure 5

IronXL is an Excel library designed for .NET developers, offering an efficient way to work with Excel and other spreadsheet formats programmatically. This library stands out for its ease of use and flexibility, allowing developers to read, write, and manipulate Excel files without needing to have Microsoft Office installed on the server or client machines.

With IronXL, you can seamlessly integrate Excel functionality into your .NET applications, enabling a wide range of operations from editing cell values to styling and formatting spreadsheets. Whether dealing with complex data reports or automating spreadsheet tasks, IronXL provides a comprehensive solution that enhances productivity.

Generate Excel Document

Here is the sample code for generating an Excel document using IronXL:

using IronXL;
// Create new Excel WorkBook document
WorkBook workBook = WorkBook.Create();
// Convert XLSX to XLS
WorkBook xlsWorkBook = WorkBook.Create(ExcelFileFormat.XLS);
// Create a blank WorkSheet
WorkSheet workSheet = workBook.CreateWorkSheet("new_sheet");
// Add data and styles to the new worksheet
workSheet["A1"].Value = "Document Generated By IronXL";
workSheet["A1"].Style.WrapText = true;
workSheet["A2"].BoolValue = true;
workSheet["A2"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Double;
// Save the excel file as XLS, XLSX, CSV, TSV, JSON, XML, HTML and streams
workBook.SaveAs("sample.xlsx");
using IronXL;
// Create new Excel WorkBook document
WorkBook workBook = WorkBook.Create();
// Convert XLSX to XLS
WorkBook xlsWorkBook = WorkBook.Create(ExcelFileFormat.XLS);
// Create a blank WorkSheet
WorkSheet workSheet = workBook.CreateWorkSheet("new_sheet");
// Add data and styles to the new worksheet
workSheet["A1"].Value = "Document Generated By IronXL";
workSheet["A1"].Style.WrapText = true;
workSheet["A2"].BoolValue = true;
workSheet["A2"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Double;
// Save the excel file as XLS, XLSX, CSV, TSV, JSON, XML, HTML and streams
workBook.SaveAs("sample.xlsx");
Imports IronXL
' Create new Excel WorkBook document
Private workBook As WorkBook = WorkBook.Create()
' Convert XLSX to XLS
Private xlsWorkBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLS)
' Create a blank WorkSheet
Private workSheet As WorkSheet = workBook.CreateWorkSheet("new_sheet")
' Add data and styles to the new worksheet
Private workSheet("A1").Value = "Document Generated By IronXL"
Private workSheet("A1").Style.WrapText = True
Private workSheet("A2").BoolValue = True
Private workSheet("A2").Style.BottomBorder.Type = IronXL.Styles.BorderType.Double
' Save the excel file as XLS, XLSX, CSV, TSV, JSON, XML, HTML and streams
workBook.SaveAs("sample.xlsx")
VB   C#

Conclusion

By following these steps, you can create Word documents in C#. The Microsoft Office Interop Word library offers a vast range of functionalities, from simple text manipulation to complex formatting. Remember, this is just the tip of the iceberg. The Interop library allows for much more detailed and complex operations, making it a powerful tool for C# developers.

IronXL offers a free trial for users to explore its features and capabilities. For those looking to integrate IronXL into their professional projects, licensing options start at $749, providing a comprehensive solution for handling Excel data within the .NET environment.