How to set the AutoFit option for word table in C#

2016-05-04 08:50:44 Written by  support iceblue
Rate this item
(0 votes)

When the contents in the word table are with the different length, the cell height of the word table will be changed and the whole table looks untidy. Microsoft Word offers AutoFit option to enable users to size a table automatically to make the word table looks beautiful. Spire.Doc also offers a method table.AutoFit() to make the AutoFit feature works well in C# for word table. This article will show you how to set the auto fit option in C# by using Spire.Doc.

Firstly, please view the Microsoft word's AutoFit feature.

How to set the AutoFit option for word table in C#

View the code snippets of how to set the AutoFit option for Sprie.Doc.

Step 1: Create a word document and load from file.

Document doc = new Document();
doc.LoadFromFile("sample.docx");

Step 2: Get the first section and the first table from the word document.

Section section = doc.Sections[0];
Table table1 = section.Tables[0] as Table;

Step 3: Call the method AutoFit() to set the rule of the AutoFit option.

table1.AutoFit(AutoFitBehaviorType.AutoFitToContents);

Step 4: Save the document to file:

doc.SaveToFile("result.docx", FileFormat.Docx); 

Effective screenshot:

How to set the AutoFit option for word table in C#

Full codes:

using Spire.Doc;
namespace SetAutofit
{
    class Program
    {

        static void Main(string[] args)
        {

            Document doc = new Document();
            doc.LoadFromFile("sample.docx");

            Section section = doc.Sections[0];
            Table table1 = section.Tables[0] as Table;

            table1.AutoFit(AutoFitBehaviorType.AutoFitToContents);

            doc.SaveToFile("result.docx", FileFormat.Docx); 
        }
    }
}

Additional Info

  • tutorial_title: Set the AutoFit option for word table in C#
Last modified on Friday, 03 September 2021 03:53