I created a Quick Table as a table template in my template dotx. I would like to create a Quick Table programmatically. is that possible?
Currently I use an existing table as template and copy its properties to the new table (see code).
object oTemplate = "D:\\Templates\\tables.dotx";
Word._Document doc = word.Documents.Add(oTemplate, ref oMissing, ref oMissing, ref oMissing);
// Copy first table as template
Word.Table tableTemplate = doc.Tables[1];
Word.Range rangeCopy = tableTemplate.Range;
rangeCopy.Copy();
...
// Reuse table template for new tables
object oMissing = Missing.Value;
var newTable = doc.Tables.Add(range, 1, 1, ref oMissing, ref oMissing);
newTable.Range.Paste();
The problem is that the dummy table is not deleted by the pasting, but moved downwards.
Solution:
- Create a Building Block in the template file (tables.dotx in my case)
- Load the Building Block in C#
- Insert into range
var template = (Word.Template)doc.get_AttachedTemplate();
Word.BuildingBlock objBB = template.BuildingBlockEntries.Item("MyCustomBlock");
objBB.Insert(range, true);
The "Quick Tables" in the
Insert > Table > Drop Down > Quick Tablelist are Building Blocks. They can also be found inInsert > Text > Quick Parts > Building Block Organizer, in the Tables gallery. This means these tables are stored in the user profile's Building Blocks template and should be part of a standard installation.The basic (VBA) code to insert a built-in (installed as part of Office) Building Block is:
And for C#
If it's uncertain that this template will have been installed, or installed to a specific file path, then the more certain approach would be to save the table as a Building Block in the template being distributed as part of VSTO solution. That's simply a matter of selecting the table then using
Insert > Text > Quick Parts > Save selection to Quick Part Gallery. In the dialog box be sure to select the template from theSave inlist as the default could well be the installation template with the building blocks.To insert a Building Block in the template from which a document was created (the "attached template"):