C#读取Word文档的详细例子C#读取Word文档的详细例子C#读取Word文档的详细例子,仅供参考,不负任何法律责任。1:对项目添加引用,MicrosoftWord11.0ObjectLibrary2:在程序中添加usingWord=Microsoft.Office.Interop.Word;3:程序中添加Word.Applicationapp=newMicrosoft.Office.Interop.Word.Application();//可以打开word程序Word.Documentdoc=null;//一会要记录word打开的文档word文档和word程序可不是一回事奥!4:一般来说,对于抽取word内容,用的方法很少publicoverridevoidopenFile(objectfileName){}//打开文档publicoverrideobjectreadPar(inti){}//读取word文档的第i段publicoverrideintgetParCount(){}//返回word文档一共几段publicoverridevoidcloseFile(){}//关闭文档publicoverridevoidquit(){}//关闭word程序//从网页上拷贝的目录有时候会出现手动换行符^l,,先将其换成回车段落标记,才能正确读取publicvoidreplaceChar(){}5:代码publicoverridevoidopenFile(objectfileName){try{if(app.Documents.Count0){if(MessageBox.Show(已经打开了一个word文档,你想关闭重新打开该文档吗?,提示,MessageBoxButtons.YesNo)==DialogResult.Yes){objectunknow=Type.Missing;doc=app.ActiveDocument;if(MessageBox.Show(你想保存吗?,保存,MessageBoxButtons.YesNo)==DialogResult.Yes){app.ActiveDocument.Save();}app.ActiveDocument.Close(refunknow,refunknow,refunknow);app.Visible=false;}else{return;}}}catch(Exception){//MessageBox.Show(您可能关闭了文档);app=newMicrosoft.Office.Interop.Word.Application();}try{objectunknow=Type.Missing;app.Visible=true;doc=app.Documents.Open(reffileName,refunknow,refunknow,refunknow,refunknow,refunknow,refunknow,refunknow,refunknow,refunknow,refunknow,refunknow,refunknow,refunknow,refunknow,refunknow);}catch(Exceptionex){MessageBox.Show(出现错误:+ex.ToString());}}publicoverrideobjectreadPar(inti){try{stringtemp=doc.Paragraphs[i].Range.Text.Trim();returntemp;}catch(Exceptione){MessageBox.Show(Error:+e.ToString());returnnull;}}publicoverrideintgetParCount(){returndoc.Paragraphs.Count;}publicoverridevoidcloseFile(){try{objectunknow=Type.Missing;objectsaveChanges=Word.WdSaveOptions.wdPromptToSaveChanges;app.ActiveDocument.Close(refsaveChanges,refunknow,refunknow);}catch(Exceptionex){MessageBox.Show(Error:+ex.ToString());}}publicoverridevoidquit(){try{objectunknow=Type.Missing;objectsaveChanges=Word.WdSaveOptions.wdSaveChanges;app.Quit(refsaveChanges,refunknow,refunknow);}catch(Exception){}}publicvoidreplaceChar(){try{objectreplaceAll=Word.WdReplace.wdReplaceAll;objectmissing=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(refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refmissing,refreplaceAll,refmissing,refmissing,refmissing,refmissing);}catch(Exceptione){MessageBox.Show(文档出现错误,请重新操作);}}6:刚才是用读取一段做的例子,如果要读取一句或一篇只需要把doc.Paragraphs[i](readPar中)改成doc.Sentences[i]或doc.content即可,因为都是微软的东东,所以用起来没有一点的障碍,再加上现在的vs2005做的很智能,所以先从java转到了c#上7:实际上,c#中读取word是不用那么麻烦的,但是如果考虑到可能还要抽取txt,ppt等多种格式,所以就写了一个抽象类,调用起来也方便,这就是为什么我的程序方法开头会有override的原因,总要考虑到通用,所以多了一些代码。