Search code examples
c#ms-worddocxdoc

Add rows to existing table in word file (doc file) using DocX dll


i have a problam with adding rows to my existing table, in my application im manipulating word file. in my template (word file) there is allready a table with 8 rows not including the header(you can see in the picture), when building a new word file in my app,sometimes i want to add more rows to the table because maybe i have more data to insert in(data from dataGridView). like in the code below, im adding rows according to how much rows i have from my datagridview,asking this:

using (DocX document = DocX.Load(filename))
{
    int k = 0;

    Table t = document.Tables[0];

    // Specify some properties for this Table.
    t.Alignment = Alignment.right;

    if (howManyRows > t.RowCount)
    {
        int x = howManyRows - t.RowCount;
        for (int i = 0; i < x; i++)
        {
            Row row = t.InsertRow();             
        }
    }      

and i tried also just: t.InsertRow();

and then im populating my table in the word file from my dataGridView and then i get an unhandled exception-index was out of range, which makes no sense,because if im not adding rows, just populating the table with the same rows number with the same code, i get no exception and the table is working fine, this is the code that i did to populate from list of string from dataGridView:

for (int i = 1; i <=howManyRows; i++)
{
    for (int j = 4; j >= 0; j--)
    {
        t.Rows[i].Cells[j].Paragraphs.First().Append(dataFromDataGrid[k]).FontSize(11).Font(new FontFamily("Arial"));
        k++;
    }
}
document.Save();

i think im not adding rows as needs to be done because if im running in my loop until :

 for (int i = 1; i <howManyRows; i++)

not like :

for (int i = 1; i <=howManyRows; i++)

as i did below, im getting this table : as the picture shows,there are no cells and borders in the rows maybe this is the problam i dont know.

My Word Table


Solution

  • i found this link

    and specifically the part about

    this.Tables[1].set_Style("Table Grid 8");

    try the style part.

    also, this link, which shows a full example, which uses

    table.Borders
    

    which looks like what you're looking for:)

    cheers

    eiran