Reputation: 4110
I opened a new question, because none of the answers I found here or elsewhere work for me.
I create a table using Word from C# (Office 16.0 Interop).
My goal: To make the width of a certain column smaller, i.e. fit to its content.
This is how I create a table:
var table = doc.Tables.Add(menuParagraph.Range, rowCount, 2, ref _objMiss, ref _objMiss);
table.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
table.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
// Label
table.Cell(1, 1).Range.Shading.BackgroundPatternColor = Word.WdColor.wdColorGray20;
table.Cell(1, 1).Range.Text = "Label";
table.Cell(1, 2).Range.Shading.BackgroundPatternColor = Word.WdColor.wdColorGray20;
table.Cell(1, 2).Range.Text = $"{recordItem.TextId.EnglishTranslation} ({recordItem.TextId.GermanTranslation})";
// Type and length
table.Cell(2, 1).Range.Text = "DataType";
table.Cell(2, 2).Range.Text = $"{recordItem.DataType} (Bit length: {recordItem.BitLength})";
// Byte offset
table.Cell(3, 1).Range.Text = "Byte offset";
table.Cell(3, 2).Range.Text = $"{recordItem.ByteOffset}";
// Default value
table.Cell(4, 1).Range.Text = "Default value";
table.Cell(4, 2).Range.Text = $"{recordItem.DefaultValue}";
None of the solutions I found so far, solved my problem.
In fact, none of it has any effect on my table.
table.Columns[0].AutoFit();
gets ignored, has no effect whatsoever.
Same goes for table.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitContent);
Even if I set the width directly, it gets ignored:
table.Columns[0].Width = app.PixelsToPoints(100f);
The output is always the same. A table where each column has the same width.
How do I force a table to make one column adjust its width to its contents (and still use the whole width of a page in total).
Upvotes: 3
Views: 11518
Reputation: 11801
For auto-fitting the first column, something like this should work. It uses the Column.SetWidth Method.
table.AllowAutoFit = true;
Word.Column firstCol = table.Columns[1];
firstCol.AutoFit(); // force fit sizing
Single firstColAutoWidth = firstCol.Width; // store autofit width
table.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitWindow); // fill page width
firstCol.SetWidth(firstColAutoWidth, Word.WdRulerStyle.wdAdjustFirstColumn); // reset width keeping right table margin
Upvotes: 3
Reputation: 7
Have you tried with : table.Columns[0].PreferredWidth ?
Maybe that would work.
Here is some documentation about it :
https://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.table.preferredwidth.aspx
Upvotes: 0