C#實現Word中表格資訊讀取

來源:互聯網
上載者:User

很多時候,會有很多資訊存放在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
其中的word任務有對word各種操作的簡單代碼案例,用vb和c#寫的。看完之後,我想每個人都會明白vb對com的支援比c#不是簡單明了一點兩點。(可以看下這個http://blog.joycode.com/kaneboy/archive/2005/08/03/61489.aspx)同樣的代碼,用vb實現開啟word文檔的操作,代碼如下:

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文檔就好。現在他們對這些難於維護,難於檢索的東西終於失去了耐性,開始考慮資料庫和網路了。也許數字化也是一個思維逐步轉變的過程。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.