Search code examples
c#.netcomms-word

Adding two tables to a word document directly on top of each other


Word has this feature where it merges tables that are inserted together, so to add two separate tables, you have to put a paragraph in between them. This has been working well, but now I need to make the paragraph go away after making the tables separate so that they're stacked on top of each other.

var document = GetDocument(word, @"C:\Blank.docx");
object missing = System.Reflection.Missing.Value;

var paragraph = document.Paragraphs.Add(ref missing);
paragraph.Range.Text = "..."; 

var table = document.Tables.Add(paragraph.Range, 1, 1, ref missing, ref missing);
table.Borders.Enable = 1;

paragraph.Range.Collapse(Microsoft.Office.Interop.Word.WdCollapseDirection.wdCollapseEnd);
paragraph.Range.InsertParagraphAfter();
paragraph.Range.Collapse(Microsoft.Office.Interop.Word.WdCollapseDirection.wdCollapseEnd);

paragraph = document.Paragraphs.Add(ref missing);
paragraph.Range.Text = "...";
table = document.Tables.Add(paragraph.Range, 1, 1, ref missing, ref missing);
table.Borders.Enable = 1;

document.Save();

var doc_close = (Microsoft.Office.Interop.Word._Document)document;
doc_close.Close();

Marshal.ReleaseComObject(document);

The top picture shows the result of the above code. I want to remove the paragraph between the two tables but don't know how to using the com object. One important thing to note is that to delete the paragraph in word, you have to press "Delete" and not "Backspace". I think that is an important hint to find the correct answer.

The top picture is the result of the above code, the bottom picture is what I want.

This example makes it seem like I want to do something that could be done with a single table, but the actual application works differently and requires two different tables that are stacked on top of each other.


Solution

  • I would try using this Lib http://docx.codeplex.com/ I found it a while back looks alot easier to use than com

    You can always use the openxml SDK for office as well but I suspect docx will be easier

    http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=5124