user2508754
user2508754

Reputation: 17

How to access each cell of a table of word document in C#

My query is that I'm using this code to get each cell of a table of a Word document

foreach (word.Table tables in doc.Tables)
{
    int r = tables.Rows.Count;
    for (int i = 1; i <= r; i++)
    {
        foreach (word.Cell cell in tables.Rows[i].Cells)
        {
            //any code
        }
    }                
}

But it's showing error if any cell in table is merged.

I want to replace text of each cell with some other text.

Upvotes: 0

Views: 8876

Answers (1)

Loathing
Loathing

Reputation: 5266

Try this, worked for me:

public static void dosomething() {
    Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
    Documents docs = app.Documents;
    Document doc = docs.Open("C:\\temp\\Test2.docx", ReadOnly:true);
    Table t = doc.Tables[1];
    Range r = t.Range;
    Cells cells = r.Cells;
    for (int i = 1; i <= cells.Count; i++) {
        Cell cell = cells[i];
        Range r2 = cell.Range;
        String txt = r2.Text;
        Marshal.ReleaseComObject(cell);
        Marshal.ReleaseComObject(r2);
    }

    //Rows rows = t.Rows;
    //Columns cols = t.Columns;
    // Cannot access individual rows in this collection because the table has vertically merged cells.
    //for (int i = 0; i < rows.Count; i++) {
    //  for (int j = 0; j < cols.Count; j++) {
    //      Cell cell = rows[i].Cells[j];
    //      Range r = cell.Range;
    //  }
    //}

    doc.Close(false);
    app.Quit(false);
    //Marshal.ReleaseComObject(cols);
    //Marshal.ReleaseComObject(rows);
    Marshal.ReleaseComObject(cells);
    Marshal.ReleaseComObject(r);
    Marshal.ReleaseComObject(t);
    Marshal.ReleaseComObject(doc);
    Marshal.ReleaseComObject(docs);
    Marshal.ReleaseComObject(app);
}

Upvotes: 2

Related Questions