使用Word API(非Openxml)打开Word文档简单示例(必须安装Word)
- 首先需要引入参照Microsoft.Office.Interop.Word
- 代码示例
1 public void OpenWord() 2 { 3 // Word应用对象 4 Word.Application wdApp = null; 5 // Word文档对象 6 Word.Document wdDoc = null; 7 8 // Word路径 9 object oWdPath = "XXXXXXXXXXXXXX"; 10 // Word设定:缺损项 11 object oMissing = System.Reflection.Missing.Value; 12 // Word设定:不保存 13 object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges; 14 15 try 16 { 17 // 新建Word应用 18 wdApp = new Word.Application(); 19 // 设置Word应用为可见 20 wdApp.Visible = true; 21 // 打开Word文档 22 wdDoc = wdApp.Documents.Open(ref oWdPath, 23 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, 24 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, 25 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); 26 } 27 finally 28 { 29 #pragma warning disable 30 // 关闭Word文档 31 if (wdDoc != null) { wdDoc.Close(); wdDoc = null; } 32 // 关闭Word应用 33 if (wdApp != null) { wdApp.Quit(ref doNotSaveChanges, ref oMissing, ref oMissing); wdApp = null; } 34 #pragma warning disable 35 GC.Collect(); 36 } 37 }
注意:
该方法必须安装Word,运行速度可能比较慢。
如只是要取得Word里面的数据,且速度要求比较高,推荐使用Openxml,而且不需要安装Word。