2011/03/18

Word字數統計

為了專案需要,經過努力的googling後,找到如何利用 Office.Interop.Word去讀取字數統計的資料,程式碼如下:

string sFillPath = "D:\\temp\\test.doc";
object Unknown = Type.Missing;

//引用Office.Interop.Word
Microsoft.Office.Interop.Word.ApplicationClass MSWord = new Microsoft.Office.Interop.Word.ApplicationClass();
Microsoft.Office.Interop.Word._Document oDoc = null;

//以word開啟doc檔
object Source = sFillPath;
oDoc = MSWord.Documents.Open(ref Source, ref Unknown,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown, ref Unknown, ref Unknown);

//讀取相關字數資料
TextBox1.Text += "字數: " + oDoc.ComputeStatistics(Microsoft.Office.Interop.Word.WdStatistic.wdStatisticWords, ref Unknown).ToString();
TextBox1.Text += "\n 頁數: " + oDoc.ComputeStatistics(Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages, ref Unknown).ToString();
TextBox1.Text += "\n 字元(不含空白): " + oDoc.ComputeStatistics(Microsoft.Office.Interop.Word.WdStatistic.wdStatisticCharacters, ref Unknown).ToString();
TextBox1.Text += "\n 全型字數: " + oDoc.ComputeStatistics(Microsoft.Office.Interop.Word.WdStatistic.wdStatisticFarEastCharacters, ref Unknown).ToString();

//關閉word實例
oDoc.Close(ref Unknown, ref Unknown, ref Unknown);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oDoc);
oDoc = null;
MSWord.Quit(ref Unknown, ref Unknown, ref Unknown);
System.Runtime.InteropServices.Marshal.ReleaseComObject(MSWord);
MSWord = null;
System.GC.Collect();

不過,因為是用Office.Interop.Word的元件,所以本機及未來的AP主機必須安裝對應的word版本,並將Office.Interop加入專案的參考。
其他字數資料所用的參數,請參見MSDN的說明。

沒有留言: