Thursday, 15 March 2012 09:31

How to Set Word Table Column Width

By using Spire.Doc, developers can create Word document with a table inside (Click to learn how to create table in Word document). But when users create table in Word document, they would not only create table with blank cells. They need set formats or sometimes set table size like column width. This article will show you how to set Word table column width.

Make sure Spire.Doc and Visual Studio are correctly installed on system. Follow the simple steps below to set Word table column width.

Step 1: Create a C# windows form application in Visual Studio. Add Spire.Doc.dll as reference. The default setting of Spire.Doc.dll is placed under "C:\Program Files\e-iceblue\Spire.Doc\Bin". Select assembly Spire.Doc.dll and click OK to add it to the project.

[C#]
using System;
using Spire.Doc;
using Spire.Doc.Fields;
using Spire.Doc.Documents;

namespace TableWidth
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
        }
    }
}
[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Fields
Imports Spire.Doc.Documents

Namespace TableWidth
	Public Partial Class Form1
		Inherits Form
		Public Sub New()
			InitializeComponent()
		End Sub
		Private Sub button1_Click(sender As Object, e As EventArgs)
		End Sub
	End Class
End Namespace

Step 2: Put the word document with table into the project folder. Use the following code to load it into project.

[C#]
Document doc = new Document();
            doc.LoadFromFile(@"..\..\Table.docx",FileFormat.Docx);
[VB.NET]
Dim doc As New Document()
doc.LoadFromFile("..\..\Table.docx", FileFormat.Docx)

Step 3: Because Spire.Doc doesn't have a direct method to set column width, we need set the first cell width of in each row.

[C#]
            for (int i = 0; i < document.Sections[0].Tables[0].Rows.Count; i++)
            {
                document.Sections[0].Tables[0].Rows[i].Cells[0].Width = 20;
            }
[VB.NET]
For i As Integer = 0 To document.Sections(0).Tables(0).Rows.Count - 1
	document.Sections(0).Tables(0).Rows(i).Cells(0).Width = 20
Next

Step 4: Save and Preview.

[C#]
document.SaveToFile(@"..\..\Sample.docx",FileFormat.Docx);
          
[VB.NET]
document.SaveToFile("..\..\Sample.docx", FileFormat.Docx)
System.Diagnostics.Process.Start("..\..\Test.pdf")

Now, the whole process is finished. Press F5 and click the button to run the project. The generated docx file can be found at the project debug folder. Check the effect.

Before Setting Width:

Word Table Column Width

After Setting Width:

Word Table Column Width

As a professional and powerful Word component, Spire.Doc doesn't need Microsoft Office Word Automation but also allows user to directly operate Word document, format and style and insert content to Word document.Click to learn more feature functions of Spire.Doc

Published in Table
Friday, 19 August 2022 08:42

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

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.RowFormat.BackColor = 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.

Published in Table
Page 3 of 3