Search code examples
c#listdocx

Add table in DocX using for-loop


I'm applications development, which has an output Microsoft word document. I use the library docx. I have a table and I need to insert the data from the List<>.

manually - work

Table t = document.AddTable(20,2);
t.Rows[0].Cells[0].Paragraphs.First().Append(listItem[0]);
t.Rows[1].Cells[0].Paragraphs.First().Append(listItem[1]);
t.Rows[2].Cells[0].Paragraphs.First().Append(listItem[2]);

I have 20 data and I do not want there to issue manually, so I tried to use a For loop, but somehow it does not work.

using For - doesn't work

for (int i = 0; i == 19; i++)
{              
    t.Rows[1 + i].Cells[0].Paragraphs.First().Append(listItem[i]);
}

document.InsertTable(t);

Solution

  • Try this:

    for (int i = 0; i <= 19; i++)
    {              
        t.Rows[i].Cells[0].Paragraphs.First().Append(listItem[i]);
    }
    
    document.InsertTable(t);
    

    Here, t.Rows is indexed from 0 to 19, which is what you'd do in the manual way too.