Spire.Doc for .NET

C#/VB.NET: Create a Table in Word

2022-08-19 08:42:00 Written by Administrator

In MS Word, the tables can organize and present data in rows and columns, which makes the information easier to understand and analyze. In this article, you will learn how to programmatically create a table with data in a Word document using Spire.Doc for .NET.

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

Create a Simple Table in Word

Below are some of the core classes and methods provided by Spire.Doc for .NET for creating and formatting tables in Word.

Name Description
Table Class Represents a table in a Word document.
TableRow Class Represents a row in a table.
TableCell Class Represents a specific cell in a table.
Section.AddTbale() Method Adds a new table to the specified section.
Table.ResetCells() Method Resets row number and column number.
Table.Rows Property Gets the table rows.
TableRow.Height Property Sets the height of the specified row.
TableRow.Cells Property Returns the cells collection.
TableRow.RowFormat Property Gets the format of the specified row.

The detailed steps are as follows

  • Create a Document object and add a section to it.
  • Prepare the data for the header row and other rows, storing them in a one-dimensional string array and a two-dimensional string array respectively.
  • Add a table to the section using Section.AddTable() method.
  • Insert data to the header row, and set the row formatting, including row height, background color, and text alignment.
  • Insert data to the rest of the rows and apply formatting to these rows.
  • Save the document to another file using Document.SaveToFile() method.
  • C#
  • VB.NET
using System;
using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace WordTable
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document object
            Document doc = new Document();
            //Add a section
            Section s = doc.AddSection();

            //Define the data for the table
            String[] Header = { "Date", "Description", "Country", "On Hands", "On Order" };
            String[][] data = {
                                  new String[]{ "08/07/2021","Dive kayak","United States","24","16"},
                                  new String[]{ "08/07/2021","Underwater Diver Vehicle","United States","5","3"},
                                  new String[]{ "08/07/2021","Regulator System","Czech Republic","165","216"},
                                  new String[]{ "08/08/2021","Second Stage Regulator","United States","98","88"},
                                  new String[]{ "08/08/2021","Personal Dive Sonar","United States","46","45"},
                                  new String[]{ "08/09/2021","Compass Console Mount","United States","211","300"},
                                  new String[]{ "08/09/2021","Regulator System","United Kingdom","166","100"},
                                  new String[]{ "08/10/2021","Alternate Inflation Regulator","United Kingdom","47","43"},
                              };
            //Add a table
            Table table = s.AddTable(true);
            table.ResetCells(data.Length + 1, Header.Length);

            //Set the first row as table header
            TableRow FRow = table.Rows[0];
            FRow.IsHeader = true;

            //Set the height and color of the first row
            FRow.Height = 23;
            FRow.Cells[i].CellFormat.Shading.BackgroundPatternColor = Color.LightSeaGreen;
            for (int i = 0; i < Header.Length; i++)
            {
                //Set alignment for cells 
                Paragraph p = FRow.Cells[i].AddParagraph();
                FRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                p.Format.HorizontalAlignment = HorizontalAlignment.Center;

                //Set data format
                TextRange TR = p.AppendText(Header[i]);
                TR.CharacterFormat.FontName = "Calibri";
                TR.CharacterFormat.FontSize = 12;
                TR.CharacterFormat.Bold = true;
            }

            //Add data to the rest of rows and set cell format
            for (int r = 0; r < data.Length; r++)
            {
                TableRow DataRow = table.Rows[r + 1];
                DataRow.Height = 20;
                for (int c = 0; c < data[r].Length; c++)
                {
                    DataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                    Paragraph p2 = DataRow.Cells[c].AddParagraph();
                    TextRange TR2 = p2.AppendText(data[r][c]);
                    p2.Format.HorizontalAlignment = HorizontalAlignment.Center;

                    //Set data format
                    TR2.CharacterFormat.FontName = "Calibri";
                    TR2.CharacterFormat.FontSize = 11;
                }
            }

            //Save the document
            doc.SaveToFile("WordTable.docx", FileFormat.Docx2013);
        }
    }
}

C#/VB.NET: Create a Table in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

In Word documents, indentation is a paragraph format used to adjust the distance between paragraph body and page margin. It includes left indent, right indent, first line indent and hanging indent. Left indent and right indent can be applied to all lines of a paragraph, while first line indent can only be applied to first line of a paragraph. As for the hanging indent, it can be applied to every line of the paragraph except the first one. This article introduces how to programmatically set paragraph indents in a Word document using Spire.Doc for .NET.

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

Set Paragraph Indents in Word

The table below lists some of the core classes and properties that are used to set different paragraph indents in a Word document.

Name Description
ParagraphFormat Class Represents the format of a paragraph.
ParagraphFormat.LeftIndent Property Returns or sets the value that represents the left indent for paragraph.
ParagraphFormat.RightIndent Property Returns or sets the value that represents the right indent for paragraph.
ParagraphFormat.FirstLineIndent Property Gets or sets the value for first line or hanging indent.  Positive value represents first-line indent, and Negative value represents hanging indent.

The detailed steps are as follows:

  • Create a Document instance.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Get a specified section using Document.Sections[] property.
  • Get a specified paragraph using Section.Paragraphs[] property.
  • Get the paragraph format using Paragraph.Format property, and then set the paragraph indent using the above listed properties of ParagraphFormat class.
  • Save the document to another file using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;

namespace WordIndent
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document doc = new Document();

            //Load a sample Word document
            doc.LoadFromFile("sample.docx");

            //Get the first paragraph and set left indent
            Paragraph para1 = doc.Sections[0].Paragraphs[0];
            para1.Format.LeftIndent = 30;

            //Get the second paragraph and set right indent
            Paragraph para2 = doc.Sections[0].Paragraphs[1];
            para2.Format.RightIndent = 30;

            //Get the third paragraph and set first line indent
            Paragraph para3 = doc.Sections[0].Paragraphs[2];
            para3.Format.FirstLineIndent = 30;

            //Get the fourth paragraph and set hanging indent
            Paragraph para4 = doc.Sections[0].Paragraphs[3];
            para4.Format.FirstLineIndent = -30;

            //Save the document to file
            doc.SaveToFile("Indent.docx", FileFormat.Docx2010);
        }
    }
}

C#/VB.NET: Set Paragraph Indents in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

A page break is a marker that controls where one page ends and where a new page begins. If you want to move the content after a certain place to the next page in your Word document, you can insert a page break. In this article, you will learn how to insert page break into Word documents in C# and VB.NET using Spire.Doc for .NET library.

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

Insert Page Break after a Specific Paragraph

The following are the steps to insert page break after a specific paragraph:

  • Create a Document instance.
  • Load a Word document using Document.LoadFromFile() method.
  • Get the desired section using Document.Sections[sectionIndex] property.
  • Get the desired paragraph using Section.Paragraphs[paragraphIndex] property.
  • Add a page break to the paragraph using Paragraph.AppendBreak(BreakType.PageBreak) method.
  • Save the result document using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;

namespace InsertPageBreakAfterParagraph
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document document = new Document();
            //Load a Word document
            document.LoadFromFile("Sample.docx");

            //Get the first section
            Section section = document.Sections[0];
            //Get the 2nd paragraph in the section
            Paragraph paragraph = section.Paragraphs[1];

            //Append a page break to the paragraph
            paragraph.AppendBreak(BreakType.PageBreak);

            //Save the result document
            document.SaveToFile("InsertPageBreak.docx", FileFormat.Docx2013);
        }
    }
}

C#/VB.NET: Insert Page Break into Word Documents

Insert Page Break after a Specific Text

The following are the steps to insert a page break after a specific text:

  • Create a Document instance.
  • Load a Word document using Document.LoadFromFile() method.
  • Find a specific text using Document.FindString() method.
  • Access the text range of the searched text using TextSelection.GetAsOneRange() method.
  • Get the paragraph where the text range is located using ParagraphBase.OwnerParagraph property.
  • Get the position index of the text range in the paragraph using Paragraph.ChildObjects.IndexOf() method.
  • Initialize an instance of Break class to create a page break.
  • Insert the page break after the searched text using Paragraph.ChildObjects.Insert() method.
  • Save the result document using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System;

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

            //Load a Word document
            document.LoadFromFile("Sample.docx");

            //Search a specific text 
            TextSelection selection = document.FindString("celebration", true, true);
            //Get the text range of the seached text
            TextRange range = selection.GetAsOneRange();
            //Get the paragraph where the text range is located
            Paragraph paragraph = range.OwnerParagraph;
            //Get the position index of the text range in the paragraph
            int index = paragraph.ChildObjects.IndexOf(range);

            //Create a page break
            Break pageBreak = new Break(document, BreakType.PageBreak);
            //Insert the page break after the searched text
            paragraph.ChildObjects.Insert(index + 1, pageBreak);

            //Save the result document
            document.SaveToFile("InsertPageBreakAfterText.docx", FileFormat.Docx2013);
        }
    }
}

C#/VB.NET: Insert Page Break into Word Documents

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

page 48