Wednesday 23 February 2011

Word Automation: Table Autofit

After struggling with trying to get a table in Open XML auto-fit itself to its contents, I gave up. I believe that the auto-fit properties are busted, and that it's the clients that are doing the auto-fit based on having rendered the contents of the columns & rows, rather than it being a property of the document itself.

Since my application requires the document to be opened in Word (in order to save it as an XPS document), I decided to go with auto-fitting the contents during the Word automation.


var wordApp = new Microsoft.Office.Interop.Word.Application();
var docPath = @"C:\temp\MyDocument.docx";
var doc = wordApp.Documents.Add(docPath);
AutoFitTables(doc);

private void AutoFitTables(_Document wordDoc)
{
foreach (Microsoft.Office.Interop.Word.Table table in wordDoc.Tables)
{
table.AutoFitBehavior(WdAutoFitBehavior.wdAutoFitContent);
table.Columns.AutoFit();
AutoFitTables(table);
}
}

private void AutoFitTables(Microsoft.Office.Interop.Word.Table table)
{
foreach (Microsoft.Office.Interop.Word.Table subTable in table.Tables)
{
subTable.AutoFitBehavior(WdAutoFitBehavior.wdAutoFitContent);
subTable.Columns.AutoFit();
AutoFitTables(subTable);
}
}

This auto-fits every table in my document, which is probably not what you want, but it's what I wanted. Well, not every table - it didn't auto-fit the table in my header, which again, is exactly what I wanted.

No comments:

Post a Comment