而我想做的是對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,如需轉載請自行聯系原作者