使用C#从doc文件中检索表数据

使用C#从doc文件中检索表数据

问题描述:

我正在从事一个涉及从.doc或.docx文件获取数据的项目.输入要求采用表格格式.是否可以以行方式或作为数据集从表中检索数据.我正在使用 Microsoft.Office.Interop.Word 从doc文件中获取数据.

I am working on a project which involves getting data from a .doc or a .docx file. The input requirements are in a tabular format. Is it possible to retrieve data from table in a row wise manner or as a dataset.I am using Microsoft.Office.Interop.Word to get the data from the doc file.

您可以使用Document接口的Tables属性来获取文档中所有表的集合.对于此集合中的每个Table,您都可以获取行,而对于每一行,则可以获取单元格.

You can use the property Tables of the Document interface to get a collection with all the tables in your document. For each Table in this collection you can get the rows and for each row the cells.

即如果app是您的Application对象,则可以编写如下代码来获取每个单元格中包含的文本(假设您的文档中恰好有一个):

I.e. if app is your Application object you can write something like this to get the text contained in each cell(supposing that there is exactly one in your doc):

    string aCellText;
    foreach (Row aRow in Application.ActiveDocument.Tables[0].Rows)
        foreach (Cell aCell in aRow.Cells)
            aCellText = aCell.Range.Text;