C#: Set the Column Width of a Word Table

Setting the column width in Word tables is crucial for optimizing document readability and aesthetics. Appropriate column widths prevent long lines of text from hindering readability, particularly in text-dense tables. Word offers two approaches: percentages and fixed values. Setting column widths using percentage values allows tables to adapt to different screen sizes, keeping content neatly aligned and enhancing the reading experience. Using fixed values, on the other hand, precisely controls the structure of the table, ensuring consistency and professionalism, making it suitable for designs with strict data alignment requirements or complex layouts. This article will introduce how to set Word table column width based on percentage or fixed value settings using Spire.Doc for .NET in C# projects.

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 Column Width Based on Percentage in C#

When setting column widths in a Word table using percentage values, you first need to set the table's preferred width type to percentage. This is done with Table.PreferredWidth = new PreferredWidth(WidthType.Percentage, (short)100). Then, iterate through each column and set the width to the same or different percentage values as required. Here are the detailed steps:

  • Create a Document object.
  • Load a document using the Document.LoadFromFile() method.
  • Retrieve the first section of the document using Document.Sections[0].
  • Get the first table within the section using Section.Tables[0].
  • Use a for loop to iterate through all rows in the table.
  • Set the column width for cells in different columns to percentage values using the TableRow.Cells[index].SetCellWidth(value, CellWidthType.Percentage) method.
  • Save the changes to the Word document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;

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

            // Load the document named "example.docx"
            doc.LoadFromFile("Sample.docx");

            // Get the first Section of the document
            Section section = doc.Sections[0];

            // Cast the first Table in the Section to Table type
            Table table = (Table)section.Tables[0];

            // Create a PreferredWidth object, set the width type to Percentage, and set the width value to 100%
            PreferredWidth percentageWidth = new PreferredWidth(WidthType.Percentage, (short)100);

            // Set the preferred width of the Table to the PreferredWidth object created above
            table.PreferredWidth = percentageWidth;

            // Define a variable of type TableRow
            TableRow tableRow;

            // Iterate through all rows in the Table
            for (int i = 0; i < table.Rows.Count; i++)
            {
                // Get the current row
                tableRow = table.Rows[i];

                // Set the width of the first column cell to 34%, with the type as Percentage
                tableRow.Cells[0].SetCellWidth(34, CellWidthType.Percentage);

                // Set the width of the second column cell to 33%, with the type as Percentage
                tableRow.Cells[1].SetCellWidth(33, CellWidthType.Percentage);

                // Set the width of the third column cell to 33%, with the type as Percentage
                tableRow.Cells[2].SetCellWidth(33, CellWidthType.Percentage);
            }

            // Save the modified document, specifying the file format as Docx2016
            doc.SaveToFile("set_column_width_by_percentage.docx", FileFormat.Docx2016);

            // Close the document
            doc.Close();
        }
    }
}

C#: Set the Column Width of a Word Table

Set Column Width Based on Fixed Value in C#

When setting column widths in a Word table using fixed values, you first need to set the table's layout to fixed. This is done with Table.TableFormat.LayoutType = LayoutType.Fixed. Then, iterate through each column and set the width to the same or different fixed values as required. Here are the detailed steps:

  • Create a Document object.
  • Load a document using the Document.LoadFromFile() method.
  • Retrieve the first section of the document using Document.Sections[0].
  • Get the first table within the section using Section.Tables[0].
  • Use a for loop to iterate through all rows in the table.
  • Set the column width for cells in different columns to fixed values using the TableRow.Cells[index].SetCellWidth(value, CellWidthType.Point) method. Note that value should be replaced with the desired width in points.
  • Save the changes to the Word document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;

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

            // Load the document
            doc.LoadFromFile("Sample.docx");

            // Get the first Section of the document
            Section section = doc.Sections[0];

            // Cast the first Table in the Section to Table type
            Table table = (Table)section.Tables[0];

            // Set the table layout type to Fixed
            table.TableFormat.LayoutType = LayoutType.Fixed;

            // Set the table resizing mode to not auto-resize
            table.TableFormat.IsAutoResized = false;

            // Get the left margin
            float leftMargin = section.PageSetup.Margins.Left;

            // Get the right margin
            float rightMargin = section.PageSetup.Margins.Right;

            // Calculate the page width minus the left and right margins
            double pageWidth = section.PageSetup.PageSize.Width - leftMargin - rightMargin;

            // Define a variable of type TableRow
            TableRow tableRow;

            // Loop through all rows in the Table
            for (int i = 0; i < table.Rows.Count; i++)
            {
                // Get the current row
                tableRow = table.Rows[i];

                // Set the width of the first column cell to 34% of the page width
                tableRow.Cells[0].SetCellWidth((float)(pageWidth * 0.34), CellWidthType.Point);

                // Set the width of the second column cell to 33% of the page width
                tableRow.Cells[1].SetCellWidth((float)(pageWidth * 0.33), CellWidthType.Point);

                // Set the width of the third column cell to 33% of the page width
                tableRow.Cells[2].SetCellWidth((float)(pageWidth * 0.33), CellWidthType.Point);
            }

            // Save the modified document, specifying the file format as Docx2016
            doc.SaveToFile("set_column_width_to_fixed_value.docx", FileFormat.Docx2016);

            // Close the document
            doc.Close();
        }
    }
}

C#: Set the Column Width of a Word Table

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.