North
North

Reputation: 109

autofit column width to contents in word automation

Using Microsoft Interop for word, after adding a table to the document, how can the column width be set for all columns so that it fits the largest item there? For example, if the column header is only two letters, and each cell underneath is only one digit, the column should only be about a centimeter wide.

Upvotes: 1

Views: 5392

Answers (2)

veevan
veevan

Reputation: 204

If you only have one table in your document, you would use something like this (where oDoc is your active document.)

oDoc.Tables(0).AllowAutoFit = True;
oDoc.Tables(0).AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitContent);

If you have more than one table, you'd want to choose the index of the one you wish to update or loop through them.

Upvotes: 3

Cindy Meister
Cindy Meister

Reputation: 25693

In the Word object model AutoFit is what the feature is called that allows (or doesn't allow) table columns to resize to fit the content, the width of the window/page or prevents them from resizing automatically.

To force the table columns to resize to fit their content:

tbl.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitContent);

To change the width of a single column to fit to the content:

tbl.Columns[index].AutoFit();

This can also be done for all columns:

tlb.Columns.AutoFit();

Upvotes: 1

Related Questions