而我想做的是对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的文章(这是一个系列的之一),再看这段代码应该不会很难理解。打开一个已有文档,然后遍历其中的所有的表。这里只是简单的将信息显示出来,具体实践上可以对这些信息进行分析。做完这些后,终于找到了一些官方的支持文档,地址如下:
<a href="http://msdn2.microsoft.com/zh-CN/library/y1xatbkd.aspx">http://msdn2.microsoft.com/zh-CN/library/y1xatbkd.aspx</a>
Dim fileName As String = "C:\Documents and Settings\liush\My Documents\TestDoc.doc"
Dim isReadOnly As Boolean = True
Dim wordApplication As Word.Application = New Word.Application()
Dim wordDocument As Word.Document
wordApplication.Visible = True
wordDocument = wordApplication.Documents.Open(fileName, , isReadOnly)
所以,下次我要做COM操作的时候,我还会回归我可爱的VB的。但是,用了太久的C#毛病越来越多了,动不动就习惯性加括号,加分号。。。
PS:这些工作是帮我老妈做的。她们资料室想把资料目录信息存入数据库,然后建立网站方便检索和管理。这些目录信息原先是存放在Word文档中的。这是她们第一次数字化的结果,那一次她们把一大堆纸质资料变成了word文档。在她们的当时理解中,数字化就是按照原来的东西,连格式都不变的变成Word文档就好。现在他们对这些难于维护,难于检索的东西终于失去了耐性,开始考虑数据库和网络了。也许数字化也是一个思维逐步转变的过程。
本文转自 duguguiyu 51CTO博客,原文链接:http://blog.51cto.com/duguguiyu/361738,如需转载请自行联系原作者