|
C#实现Word中表格信息读取(1) 很多时候,会有很多信息存放在Word文档中。而我们需要把这些信息提取出来,另做它用。而Word的格式是ms的机密,不知道有没有NB人可以对其做字符流的分析,反正我是没这能力也没这打算。所以就只能用ms提供的组件来进行编程。但ms没有提供托管的类库,而是提供了对com组件的PIA转换。具体添加,使用和相关知识,可以参见kaneboy's blog中的http://blog.joycode.com/kaneboy/articles/67688.ASPx。高手的讲解,很是清晰。 而我想做的是对word文档中的表信息进行提取。网上很难找到相关的代码(打开一个已有文档,对其内容进行分析),但我觉得这种工作是很有意义的。写了一段小的Demo,如下:
object oFileName = @"C:\Documents and Settings\liush\My Documents\TestDoc.doc"; object oReadOnly = true; object oMissing = System.Reflection.Missing.Value;
Word._Application oWord; Word._Document oDoc; oWord = new Word.Application(); oWord.Visible = true;//只是为了方便观察 oDoc = oWord.Documents.Open(ref oFileName, ref oMissing, ref oReadOnly, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
//MessageBox.Show(oDoc.Tables.Count.ToString()); for (int tablePos = 1; tablePos <= oDoc.Tables.Count; tablePos++) { Word.Table nowTable = oDoc.Tables.Item(tablePos); string tableMessage = string.Format("第{0}/{1}个表:\n", tablePos, oDoc.Tables.Count);
for (int rowPos = 1; rowPos <= nowTable.Rows.Count; rowPos++) { for (int columPos = 1; columPos <= nowTable.Columns.Count; columPos++) { tableMessage += nowTable.Cell(rowPos, columPos).Range.Text; tableMessage = tableMessage.Remove(tableMessage.Length - 2, 2);//remove \r\a tableMessage += "\t"; }
tableMessage += "\n"; }
MessageBox.Show(tableMessage); }
如果看过了上面kaneboy的文章(这是一个系列的之一),再看这段代码应该不会很难理解。打开一个已有文档,然后遍历其中的所有的表。这里只是简单的将信息显示出来,具体实践上可以对这些信息进行分析。做完这些后,终于找到了一些官方的支持文档,地址如下: http://msdn2.microsoft.com/zh-CN/library/y1xatbkd.aspx
|