//從網頁上拷貝的目錄有時候會出現手動換行符^l,,先將其換成回車段落標記,才能正確讀取
public void replaceChar(){}
5:代碼
public override void openFile(object fileName)
...{
try
...{
if (app.Documents.Count > 0)
...{
if (MessageBox.Show("已經打開了一個Word文檔,你想關閉重新打開該文檔嗎?", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
...{
object unknow = Type.Missing;
doc = app.ActiveDocument;
& if (MessageBox.Show("你想保存嗎?", "保存", MessageBoxButtons.YesNo) == DialogResult.Yes)
...{
app.ActiveDocument.Save();
}
app.ActiveDocument.Close(ref unknow, ref unknow, ref unknow);
app.Visible = false;
}
else
...{
return;
}
}
}
catch (Exception)
...{
//MessageBox.Show("您可能關閉了文檔");
app = new Microsoft.Office.Interop.Word.Application();
}
try
...{
object unknow = Type.Missing;
app.Visible = true;
doc = app.Documents.Open(ref fileName,
ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);
}
catch (Exception ex)
...{
MessageBox.Show("出現錯誤:" + ex.ToString());
}
}
public override object readPar(int i)
...{
try
...{
string temp = doc.Paragraphs[i].Range.Text.Trim();
return temp;
}
catch (Exception e) ...{
MessageBox.Show("Error:"+e.ToString());
return null;
}
}
public override int getParCount()
...{
return doc.Paragraphs.Count;
}
public override&nbcloseFile()
...{
try
...{
object unknow = Type.Missing;
object saveChanges = Word.WdSaveOptions.wdPromptToSaveChanges;
app.ActiveDocument.Close(ref saveChanges, ref unknow, ref unknow);
}
catch (Exception ex)
...{
MessageBox.Show("Error:" + ex.ToString());
}
}
public override void quit()
...{
try
...{
object unknow = Type.Missing;
object saveChanges = Word.WdSaveOptions.wdSaveChanges;
app.Quit(ref saveChanges, ref unknow, ref unknow);
}
catch (Exception)
...{
}
}

public void replaceChar() ...{
try
...{
object replaceAll = Word.WdReplace.wdReplaceAll;
object missing = Type.Missing;
app.Selection.Find.ClearFormatting();
app.Selection.Find.Text = "^l";
app.Selection.Find.Replacement.ClearFormatting();
app.Selection.Find.Replacement.Text = "^p";
app.Selection.Find.Execute(
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref replaceAll, ref missing, ref missing, ref missing, ref missing);
}
catch (Exception e)
...{
MessageBox.Show("文檔出現錯誤,請重新操作");
}
}
6:
剛才是用讀取一段做的例子,如果要讀取一句或一篇只需要把doc.Paragraphs[i](readPar中)改成doc.Sentences[i]或doc.content即可,因為都是微軟的東東,所以用起來沒有一點的障礙,再加上現在的vs2005做的很智能,所以先從Java轉到了c#上
7:
實際上,c#中讀取Word是不用那麼麻煩的,但是如果考慮到可能還要抽取txt,PPT等多種格式,所以就寫了一個抽象類,調用起來也方便,這就是為什麼我的程序方法開頭會有override的原因,總要考慮到通用,所以多了一些代碼。