How to Create Word Document in C#

By Tan Lee Published on Jan 17, 2025  386
Creating a Word document programmatically in C# can be achieved using the Microsoft.Office.Interop.Word library.

This library allows you to interact with Microsoft Word, enabling you to create, modify, and save Word documents directly from your C# application.

Prerequisites

Before diving into the code, ensure the following prerequisites are met:

  1. Microsoft Office Installation: MS Office must be installed on your machine.
  2. Project Setup: Create a Console or Windows application in Visual Studio.
  3. Add Reference: Add a reference to the Microsoft.Office.Interop.Word library.
    You can find this DLL at:
    C:\Windows\assembly\GAC_MSIL\Microsoft.Office.Interop.Word\15.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Word.dll.

Below is a sample implementation of creating a Word document with a header, content, and a table.

For example, word c# document create

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
private void CreateWordDocument(string header, string wholeData)
{
    Microsoft.Office.Interop.Word.Application winword = null;
    Microsoft.Office.Interop.Word.Document document = null;
 
    try
    {
        // Initialize Word application
        winword = new Microsoft.Office.Interop.Word.Application
        {
            ShowAnimation = false,
            Visible = false
        };
 
        // Create a new document
        object missing = System.Reflection.Missing.Value;
        document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);
 
        // Add Header
        AddParagraph(document, header, "Heading 1");
 
        // Add Content
        AddParagraph(document, wholeData, fontSize: 14);
 
        // Add Table
        AddSampleTable(document);
 
        // Save Document
        string sanitizedHeader = ReplaceInvalidFileNameChars(header);
        string filePath = $@"C:\YourOutputPath\{sanitizedHeader}.docx";
        document.SaveAs2(filePath);
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error: {ex.Message}");
    }
    finally
    {
        // Cleanup
        document?.Close(false);
        winword?.Quit(false);
    }
}
 
private void AddParagraph(Microsoft.Office.Interop.Word.Document document, string text, string style = null, int? fontSize = null)
{
    object missing = System.Reflection.Missing.Value;
    var paragraph = document.Content.Paragraphs.Add(ref missing);
 
    if (!string.IsNullOrEmpty(style))
    {
        paragraph.Range.set_Style(style);
    }
 
    if (fontSize.HasValue)
    {
        paragraph.Range.Font.Size = fontSize.Value;
    }
 
    paragraph.Range.Text = text;
    paragraph.Range.InsertParagraphAfter();
}
 
private void AddSampleTable(Microsoft.Office.Interop.Word.Document document)
{
    object missing = System.Reflection.Missing.Value;
    var range = document.Content.Paragraphs[1].Range; // Use the first paragraph's range
    var table = document.Tables.Add(range, 2, 1, ref missing, ref missing);
 
    table.Borders.Enable = 1;
    foreach (Row row in table.Rows)
    {
        foreach (Cell cell in row.Cells)
        {
            if (cell.RowIndex == 1)
            {
                cell.Range.Text = $"Sample Code {cell.ColumnIndex}";
                cell.Range.Font.Bold = 1;
                cell.Range.Font.Name = "Verdana";
                cell.Shading.BackgroundPatternColor = WdColor.wdColorGray25;
                cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
            }
            else
            {
                cell.Range.Text = "SQL or C# code sample will appear here";
            }
        }
    }
}
 
private string ReplaceInvalidFileNameChars(string input)
{
    return string.Concat(input.Select(c => Path.GetInvalidFileNameChars().Contains(c) ? ' ' : c));
}

Usage

1
CreateWordDocument("MyHeader", "This is the content of the document.");

In this example:

  • Header and Content: The Paragraph objects are used to add headers and content with specific styles and formatting.
  • Table Creation: A 1x2 table is created using the Tables.Add method, where each cell can contain custom text and formatting.
  • File Saving: The file is saved with a name derived from the header parameter. Special characters are removed to avoid errors.