如何在C#中访问word文档表的每个单元格

时间:2014-06-06 04:45:57

标签: c#-4.0

我的疑问是我使用此代码获取Word文档表格的每个单元格

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
        }
    }                
}

但如果合并了表格中的任何单元格,它会显示错误。

我想用其他文本替换每个单元格的文本。

1 个答案:

答案 0 :(得分:1)

试试这个,为我工作:

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);
}