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.
- Add Titles, Headings, and Paragraphs to a Word Document
- Add an Image to a Word Document
- Add a Table to a Word Document
- Add a List to a 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
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 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 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 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 ListStyle().
- 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#
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace AddList { 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; // Create a bulleted list style ListStyle listStyle = new ListStyle(document, ListType.Bulleted); listStyle.Name = "bulletedList"; listStyle.Levels[0].BulletCharacter = "\x00B7"; listStyle.Levels[0].CharacterFormat.FontName = "Symbol"; listStyle.Levels[0].TextPosition = 20; document.ListStyles.Add(listStyle); // 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.Name); 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(); } } }
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.