Friday, 11 April 2025 01:33

C#: Create a Word Document from Scratch

Generating Word documents programmatically in C# is a powerful way to automate report creation, invoices, or any other dynamic document. With Spire.Doc for .NET, a robust and easy-to-use library, you can efficiently build Word files from scratch with full control over formatting and content. This guide will walk you through key features such as adding titles, headings, and paragraphs for structured text, inserting images for visual elements, creating tables to organize data, and adding lists for better readability.

By leveraging Spire.Doc, you can seamlessly generate professional, well-formatted Word documents directly from your .NET applications. Let's dive in and explore how to implement these functionalities step by step.

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

Add Titles, Headings, and Paragraphs to a Word Document in C#

When creating structured Word documents with Spire.Doc for .NET, the core functionality revolves around the Document and Section classes. New paragraphs are added using AddParagraph(), while text content is inserted via AppendText(). For consistent formatting, you can apply built-in styles such as Title or Heading 1-4, which ensure a professional and standardized layout. Alternatively, custom styles can be defined for precise control over fonts, colors, and sizing, allowing for tailored document design.

Steps for adding titles, headings, and parargraphs to a Word documents in C#:

  • Create a Document object.
  • Add a section to the document with Document.AddSection().
  • Add paragraphs to the section using Section.AddParagraph().
  • Use Paragraph.ApplyStyle() to apply built-in styles (Title, Heading1, Heading2, Heading3) to specific paragraphs.
  • Define a custom paragraph style with ParagraphStyle() and apply it to a designated paragraph.
  • Save the document as a DOCX file.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

namespace CreateSimpleWordDocument
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document document = new Document();

            // Add a section
            Section section = document.AddSection();

            // Set page margins
            section.PageSetup.Margins.All = 60f;

            // Add a title paragraph
            Paragraph title_para = section.AddParagraph();
            TextRange textRange = title_para.AppendText("This Is Title");
            title_para.ApplyStyle(BuiltinStyle.Title);
            textRange.CharacterFormat.FontName = "Times Now Roman";

            // Add a couple of heading paragraphs
            Paragraph heading_one = section.AddParagraph();
            textRange = heading_one.AppendText("Heading 1");
            heading_one.ApplyStyle(BuiltinStyle.Heading1);
            textRange.CharacterFormat.FontName = "Times Now Roman";

            Paragraph heading_two = section.AddParagraph();
            textRange = heading_two.AppendText("Heading 2");
            heading_two.ApplyStyle(BuiltinStyle.Heading2);
            textRange.CharacterFormat.FontName = "Times Now Roman";

            Paragraph heading_three = section.AddParagraph();
            textRange = heading_three.AppendText("Heading 3");
            heading_three.ApplyStyle(BuiltinStyle.Heading3);
            textRange.CharacterFormat.FontName = "Times Now Roman";

            Paragraph heading_four = section.AddParagraph();
            textRange = heading_four.AppendText("Heading 4");
            heading_four.ApplyStyle(BuiltinStyle.Heading4);
            textRange.CharacterFormat.FontName = "Times Now Roman";

            // Add a normal paragraph
            Paragraph normal_para = section.AddParagraph();
            normal_para.AppendText("This is a sample paragraph.");

            // Create a paragraph style
            ParagraphStyle style = new ParagraphStyle(document);
            style.Name = "paraStyle";
            style.CharacterFormat.FontName = "Times New Roman";
            style.CharacterFormat.FontSize = 13f;
            style.CharacterFormat.TextColor = Color.Brown;
            document.Styles.Add(style);

            // Apply the custom style to the paragraph
            normal_para.ApplyStyle("paraStyle");

            // Save the document
            document.SaveToFile("AddText.docx", FileFormat.Docx);

            // Dispose resources
            document.Dispose();
        }
    }
}

Add title, heading and paragraph to a Word document

Add an Image to a Word Document in C#

To insert an image into a Word document, first create a dedicated paragraph element to serve as the image container. By using the AppendPicture() method, you can load an image from the file system and embed it directly into the document structure.

Steps for adding an image to a Word doucment in C#:

  • Create a Document object.
  • Add a section to the document with Document.AddSection().
  • Add a paragraph to the section using Section.AddParagraph().
  • Use the Paragraph.AppendPicture() method to add an image to the paragraph.
  • Save the document as a DOCX file.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;

namespace AddImage
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document document = new Document();

            // Add a section
            Section section = document.AddSection();

            // Set page margins
            section.PageSetup.Margins.All = 60f;

            // Add a paragraph
            Paragraph image_para = section.AddParagraph();

            // Append an image
            image_para.AppendPicture(Image.FromFile("C:\\Users\\Administrator\\Desktop\\logo.png"));
      
            //Save the document
            document.SaveToFile("AddImage.docx", FileFormat.Docx);

            // Dispose resources
            document.Dispose();
        }
    }
}

Add image to a Word document

Add a Table to a Word Document in C#

The table creation process begins with the AddTable() method, which establishes the basic table structure. You can precisely define the table dimensions by specifying the required number of rows and columns through the ResetCells() method. Once initialized, each cell can be populated by first adding a paragraph element using AddParagraph(), then inserting your textual content with AppendText().

Steps for adding a table to a Word document in C#:

  • Create a Document object.
  • Add a section to the document with Document.AddSection().
  • Create a two-dimensional array to hold the table data, including headers and values.
  • Use Section.AddTable() to create a table.
  • Call Table.ResetCells() to define the number of rows and columns in the table based on your data.
  • Iterate through the data array, adding text to each cell using the TableCell.AddParagraph() and Paragraph.AppendText() methods.
  • Save the document as a DOCX file.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;

namespace AddTable
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document document = new Document();

            // Add a section
            Section section = document.AddSection();

            // Set page margins
            section.PageSetup.Margins.All = 60f;

            // Define table data as a 2D array
            string[,] data = new string[4, 4]
            {
                { "Product", "Unit Price", "Quantity", "Sub Total" },
                { "A", "$29", "120", "$3,480" },
                { "B", "$35", "110", "$3,850" },
                { "C", "$68", "140", "$9,520" }
            };

            // Add a table
            Table table = section.AddTable(showBorder: true);

            // Set row number and column number
            table.ResetCells(data.GetLength(0), data.GetLength(1));

            // Write data to cells
            for (int r = 0; r < data.GetLength(0); r++)
            {
                TableRow row = table.Rows[r];
                row.Height = 20;
                row.HeightType = TableRowHeightType.Exactly;

                for (int c = 0; c < data.GetLength(1); c++)
                {
                    var cell = row.Cells[c];
                    cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                    var textRange = cell.AddParagraph().AppendText(data[r, c]);
                    textRange.CharacterFormat.FontName = "Times New Roman";
                    textRange.CharacterFormat.FontSize = 14;
                }
            }

            // Automatically adjusts the column widths of a table to fit its contents
            table.AutoFit(AutoFitBehaviorType.AutoFitToContents);

            // Save the document to file
            document.SaveToFile("AddTable.docx", FileFormat.Docx);

            // Dispose resources
            document.Dispose();
        }
    }
}

Add table to a Word document

Add a List to a Word Document in C#

The ListStyle class provides the foundation for implementing both bulleted and numbered lists in your document. By configuring this class, you can establish consistent visual formatting for all list items. Once your list style is defined, simply apply it to target paragraphs using the ApplyStyle() method.

Steps for adding a list to a Word document in C#:

  • Create a Document object.
  • Add a section to the document with Document.AddSection().
  • Define a list style using Document.Styles.Add().
  • Add paragraphs to the section using Section.AddParagraph().
  • Apply the defined list style to the paragraphs using Paragraph.ListFormat.ApplyStyle().
  • Save the document as a DOCX file.
  • C#
// Create a Document object
Document document = new Document();

// Add a section
Section section = document.AddSection();

// Set page margins
section.PageSetup.Margins.All = 60f;

// Create a bulleted list style
ListStyle listStyle = document.Styles.Add(ListType.Bulleted, "bulletedList");
ListLevelCollection Levels = listStyle.ListRef.Levels;
Levels[0].BulletCharacter = "\x00B7";
Levels[0].CharacterFormat.FontName = "Symbol";
Levels[0].TextPosition = 20;

// Add a paragraph
Paragraph paragraph = section.AddParagraph();
TextRange textRange = paragraph.AppendText("Fruits:");
paragraph.Format.AfterSpacing = 5f;
textRange.CharacterFormat.FontName = "Times New Roman";
textRange.CharacterFormat.FontSize = 14;

// Add another five paragraphs as bulleted list items
foreach (var fruit in new[] { "Apple", "Banana", "Watermelon", "Mango" })
{
    paragraph = section.AddParagraph();
    textRange = paragraph.AppendText(fruit);
    paragraph.ListFormat.ApplyStyle(listStyle);
    paragraph.ListFormat.ListLevelNumber = 0;
    textRange.CharacterFormat.FontName = "Times New Roman";
    textRange.CharacterFormat.FontSize = 14;
}

// Save the document to file
document.SaveToFile("AddList.docx", FileFormat.Docx);

// Dispose resources
document.Dispose();

 Add list to a Word document

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.

Tuesday, 14 December 2010 07:23

Spire.Doc for .NET Program Guide Content

Spire.Doc for .NET is a professional Word .NET library specifically designed for developers to create, read, write, convert, compare and print Word documents on any .NET platform (Target .NET Framework, .NET Core, .NET Standard, .NET 5.0, .NET 6.0, Xamarin & Mono Android) with fast and high quality performance.

As an independent Word .NET API, Spire.Doc for .NET doesn't need Microsoft Word to be installed on neither the development nor target systems. However, it can incorporate Microsoft Word document creation capabilities into any developers' .NET applications.

Thursday, 09 December 2010 04:10

Solutions to Open Word in C#, VB.NET

No matter what users want to do on Word document, they should open it. This guide demonstrates several solutions to open Word in C# and VB.NET via Spire.Doc for .NET.

Open Existing Word

Spire.Doc for .NET provides a Document(String) constructor to enable users to initialize a new instance of Document class from the specified existing document.

[C#]
  Document document = new Document(@"E:\Work\Documents\Spire.Doc for .NET.docx");
[VB.NET]
Dim document As New Document("E:\Work\Documents\Spire.Doc for .NET.docx")

Spire.Doc for .NET also provides Document.LoadFromFile(String) method of Document class to open a Word document. The Word document can be .doc(Word 97-2003), .docx(Word 2007 and 2010) and .docm(Word with macro).

[C#]
  Document document = new Document();
            document.LoadFromFile(@"E:\Work\Documents\Spire.Doc for .NET.docx");
[VB.NET]
 Dim document As New Document()
            document.LoadFromFile("E:\Work\Documents\Spire.Doc for .NET.docx")
          

Open Word in Read Mode

Spire.Doc for .NET provides Document.LoadFromFileInReadMode(String, FileFormat) method of Document class to load Word in Read-Only mode.

[C#]
            Document document = new Document();
            document.LoadFromFileInReadMode(@"E:\Work\Documents\Spire.Doc for .NET.docx",FileFormat.Docx);
[VB.NET]
            Dim document As New Document()
            document.LoadFromFileInReadMode("E:\Work\Documents\Spire.Doc for .NET.docx", FileFormat.Docx)

Load Word from Stream

Spire.Doc for .NET provides the constructor Document(Stream) to initialize a new instance of Document class from specified data stream and the method Document.LoadFromStream(Stream, FileFormat) to open document from Stream in XML or Microsoft Word document.

[C#]
            Stream stream = File.OpenRead(@"E:\Work\Documents\Spire.Doc for .NET.docx");
            Document document = new Document(stream);
OR
            Stream stream = File.OpenRead(@"E:\Work\Documents\Spire.Doc for .NET.docx");
            Document document = new Document();
            document.LoadFromStream(stream, FileFormat.Docx);
[VB.NET]
            Dim stream As Stream = File.OpenRead("E:\Work\Documents\Spire.Doc for .NET.docx")
            Dim document As New Document(stream)
OR
            Dim stream As Stream = File.OpenRead("E:\Work\Documents\Spire.Doc for .NET.docx")
            Dim document As New Document()
            document.LoadFromStream(stream, FileFormat.Docx)

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.

Saturday, 04 December 2010 10:35

Licensing

Each product of e-iceblue provides a trial version, every registered user can download them from our site for free. The trial version product will add an extra sheet (in Spire.XLS) or paragraph (in Spire.Doc) with the Evaluation Warning to the result file. From Spire.Doc v3.6.0/Spire.XLS v5.8.0/Spire.Office 1.4.0, We deprecated the old username-key registeration method and use a new license file to instead. When you purchase a license, you will get a license file from us. After you apply it, the Evaluation Warning will disappear.

This section will show you what is the license file and how to apply the license file. It includes following topics:


License File Introduction

The license file is an XML format file that contains details such as the username&email&organization of the purchaser, licensing date, product name, product version, the number of licensed developer, the number of licensed site and so on. The license file is digitally signed, so do not modify it anyway.

You need to apply it before performing any operations with our products, but it's only required once to apply the license file in an application or process.


How to Apply the License File

Performing any operation with our products will lead the license module to check whether the license has been loaded. If not, the license module will try to load it. The license can be loaded implicitly or explicitly from a file, stream or an embedded resource, implicit is default.

Note: Whether implicity or explicity, you must apply the license file before you call any of our products.

Implicit Loading

In this mode, the license module will try to search the license file in the following locations:

  • The folder that contains the entry assembly (your assembly named .exe) in runtime.
  • An embedded resource in the assembly that calls our product.
  • The folder that contains the assembly of our product (for example: Spire.Doc.dll, Spire.XLS.dll) referenced by your assembly in runtime.
  • The folder that contains the assembly that calls our product in runtime.

When you get the license file from us, the default name of it is license.elic.xml. You can put it in any location aforementioned. The license module will load it automatically in your application. You can also change the license file name. If you do that, it's required to tell the license module the new file name before you perform any operation with our products, for example:

  • C#
  • VB.NET
//Tell the license module that you changed the license file name.
Spire.License.LicenseProvider.SetLicenseFileName("your-license-file-name");

You can also get the license file name by which the license module search the license, for example:

  • C#
  • VB.NET
//To get the default license file name.
String fileName = Spire.License.LicenseProvider.GetLicenseFileName();

Explicit Loading

In this mode, the license module will try to load the license from a specified file or stream you provide.

Explicitly specify the license file by a full file name.

  • C#
  • VB.NET
//Specify the license file by a full file name.
Spire.License.LicenseProvider.SetLicenseFileFullPath(@"D:\myApp\license.lic.xml");

Explicitly specify the license file by a FileInfo object.

  • C#
  • VB.NET
//Specify the license file by a FileInfo object.
FileInfo licenseFile = new FileInfo(@"D:\myApp\license.lic.xml");
Spire.License.LicenseProvider.SetLicenseFile(licenseFile);

Provide a license data stream.

  • C#
  • VB.NET
//Specify the license by a license data stream.
Stream stream = File.OpenRead(@"D:\myApp\license.lic.xml");
Spire.License.LicenseProvider.SetLicenseFileStream(stream);

See also: How to Apply the License by license key


How to Include the License File as an Embedded Resource

Including the license file as an embedded resource into one of the assemblies that calls our products is a good idea. It will make your release and deployment become easier. You don't need to worry about the loss of it any longer. To include the license file as an embedded resource in Visual Studio, perform the following steps:

  • In the Solution Explorer, right-click your project and click Add | Add Existing Item... menu.
  • Find your license file in the opend file browser dialog, then click the Add button to add it into your project.
  • Select the file in the Solution Explorer and set Build Action to Embedded Resource in the Properties window.
  • If your license file name is not the default file name license.elic.xml, invoke Spire.License.LicenseProvider.SetLicenseFileName to tell the real name to the license module in your code.

Embedded License

See also: How to Apply the License by license key


How to Apply the License File in a Web Site

If you want to apply the license file in a web site, just copy it into the folder Bin which contains the referenced assemblies of your web site.

Copy License

See also: How to Apply the License by license key


How to Apply the License by license key

Sometimes, your application could not read the license file because of lack of permission or other reason. In this case, you can invoke the method Spire.License.LicenseProvider.SetLicenseKey(String key) to apply your license. The parameter key is the value of the Key attribute of the element License of your license xml file. To make sure that apply the license before any operation with our products, we recommend invoking this method in the top of your entry method.

  • C#
  • VB.NET
//Register the license key
Spire.License.LicenseProvider.SetLicenseKey("your license key");
//Spire.Doc version 11.5.6 or above
Spire.Doc.License.LicenseProvider.SetLicenseKey("your license key");
//Spire.XLS  version 13.6.0 or above
Spire.Xls.License.LicenseProvider.SetLicenseKey("your license key");
//Spire.PDF version 9.6.0 or above
Spire.Pdf.License.LicenseProvider.SetLicenseKey("your license key");
//Spire.Presentation version 8.6.0 or above
Spire.Presentation.License.LicenseProvider.SetLicenseKey("your license key");

 

  • Java
//Register the license key
com.spire.license.LicenseProvider.setLicenseKey("your license key");
//Spire.Doc version 12.1.10 or above
com.spire.doc.license.LicenseProvider.setLicenseKey("Key"); 
//Spire.XLS version 14.1.3 or above
com.spire.xls.license.LicenseProvider.setLicenseKey("Key");
//Spire.Presentation version 9.1.2 or above
com.spire.presentation.license.LicenseProvider.setLicenseKey("Key");
//Spire.PDF version 10.1.9 or above
com.spire.pdf.license.LicenseProvider.setLicenseKey("Key"); 
//Spire.Ocr version 1.9.3 or above
com.spire.ocr.license.LicenseProvider.setLicenseKey("Key"); 
//Spire.Barcode version 5.1.3 or above
com.spire.barcode.license.LicenseProvider.setLicenseKey("Key"); 

 

  • C++
//Spire.Doc
Spire::Doc::License::SetLicenseKey("your license key")
//Spire.XLS
Spire::Xls::License::SetLicenseKey("your license key")
//Spire.Presentation
Spire::Presentation::License::SetLicenseKey("your license key")
//Spire.PDF
Spire::Pdf::License::SetLicenseKey("your license key")

 

  • Python
from spire.doc import *
from spire.pdf import *
from spire.xls import *
from spire.presentation import *
from spire.presentation import LicenseProvider as pptLicense
from spire.pdf import LicenseProvider as pdfLicense
from spire.doc import LicenseProvider as docLicense
from spire.xls import LicenseProvider as xlsLicense

# Apply license for Spire.PDF
pdfLicense.SetLicenseKey(key)

# Apply license for Spire.Doc
docLicense.SetLicenseKey(key)

# Apply license for Spire.XLS
xlsLicense.SetLicenseKey(key)

# Apply license for Spire.Presentation
pptLicense.SetLicenseKey(key)
  • If your application is WinForm Application or Console Application, this code above should be added into the Main method.
  • If your application is ASP.NET Application, you need to add Global.asax into your project and add this method code above into the Application_Start method.
  • If your application is ASP.NET Core Application, this code above should be added into the Startup method of Startup.cs.

How to Apply two licenses or more

When you need to use two products in the same project,such as Spire.Doc and Spire.XLS, Spire.Presentation and Spire.XLS, you need to download Spire.Office to use them together and there is no need for you to purchase Spire.Office. Please refer to how to apply two license to use Spire.Office normally by applying the license files you purchased.

If you apply your 2 licenses or more by license key, you can invoke the following method in the top of your entry method.

  • C#
  • Java
Spire.Doc.License.LicenseProvider.SetLicenseKey("your license key");
Spire.Doc.License.LicenseProvider.LoadLicense();
Spire.Xls.License.LicenseProvider.SetLicenseKey("your license key");  
Spire.Xls.License.LicenseProvider.LoadLicense();
Spire.Pdf.License.LicenseProvider.SetLicenseKey("your license key");  
Spire.Pdf.License.LicenseProvider.LoadLicense();
Spire.Presentation.License.LicenseProvider.SetLicenseKey("your license key");  
Spire.Presentation.License.LicenseProvider.LoadLicense();

If you apply them by license file, you can invoke the following method:

  • C#
Spire.License.LicenseProvider.SetLicenseFileName("license1.elic.xml");  
Spire.License.LicenseProvider.LoadLicense();  
Spire.License.LicenseProvider.SetLicenseFileName("license2.elic.xml");  
Spire.License.LicenseProvider.LoadLicense();
Thursday, 21 October 2010 14:19

Word Page Setup in C#, VB.NET

The sample demonstrates how to work with Word page setup.

Thursday, 21 October 2010 14:16

Word document setup in C#, VB.NET

The sample demonstrates how to set document properties.

Thursday, 21 October 2010 13:51

Word merge event handler in C#, VB.NET

The sample demonstrates how to handle merge event.

Thursday, 21 October 2010 13:47

Word to pdf in C#, VB.NET

The sample demonstrates how to export doc document to PDF file.

Thursday, 21 October 2010 13:44

Word to xml in C#, VB.NET

The sample demonstrates how to export doc document to XML file.

 

Thursday, 21 October 2010 13:34

Word to Tiff image in C#, VB.NET

The sample demonstrates how to export doc document to TIFF image.