Search code examples
c#ms-wordoffice-interopoffice-automationword-interop

Creating multiple tables dynamically on Word using C#


First of all let me start by saying I'm coming over from Javascript to C# and have never used the Word Interop before so forgive me if I make any stupid mistakes.

I'm trying to create a series of tables from a single List. What I was thinking was, everytime a new value under the "TableName" element is introduced it creates a new table, and keeps adding rows to existing table until another new TableName is introduced.

Here's what I got so far

using Word = Microsoft.Office.Interop.Word;


Word._Application oWord;
Word._Document oDoc;
object oMissing = System.Reflection.Missing.Value;
object oTemplate = //Location of Template file in my Local drive
int i = 0;

for (int j = 0; j < TableList.Count; j++)
{
    if (TableList[j].TableName != tableHolder)
    {
        i++;
        tableHolder = TableList[j].TableName;


        oDoc.Tables.Add(wrdRng, 1, 6, ref oMissing, ref oMissing);
        Word.Table oTable = oDoc.Tables[i];
        oTable.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
        oTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
        //Adding values to individual cells here
        wrdRng = oDoc.Tables[i].Range;
        wrdRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
        wrdRng.InsertParagraphAfter();
        wrdRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
    }
    else
    {
        //add rows to Tables[i]
    }
}

I'm 95% sure my problem is oDoc.Tables[i];, but at this point, I'm not even sure if it can be done, every example I see at other StackOverflow forums show the user having a pre-determined number of tables.

Could someone help me out here?


Solution

  • So I figured out the issue, instead of

    oDoc.Tables.Add(wrdRng, 1, 6, ref oMissing, ref oMissing);
    Word.Table oTable = oDoc.Tables[i];
    

    it should've been

    Word.Table oTable;
    oTable = oDoc.Tables[i];
    oTable = oDoc.Tables.Add(wrdRng, 1, 6, ref oMissing, ref oMissing);