思享者

知其然亦知其所以然,以至不惑也

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
 1 using Word = Microsoft.Office.Interop.Word;
2
3 // 创建Word文档
4 Word.Application WordApp = null;
5 Word.Document WordDoc = null;
6
7 Object Nothing = System.Reflection.Missing.Value;
8 WordApp = new Word.ApplicationClass();
9 WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
10
11 // Word文件路径
12 string filename = System.Windows.Forms.Application.StartupPath + "\\test.doc";
13 string message = "";
14
15 try
16 {
17 // 创建Word文档
18 // ... ...
19 }
20 catch (Exception ex)
21 {
22 MessageBox.Show(message = "文件导出异常!" + ex.ToString());
23 }
24 finally
25 {
26 //文件保存
27 WordDoc.SaveAs(ref filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
28 WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
29
30 // Solution-1
31 object saveOption = Word.WdSaveOptions.wdDoNotSaveChanges;
32 WordApp.Quit(ref saveOption, ref Nothing, ref Nothing);
33 }

解决方案 二

 1             try
2 {
3 if (WordDoc != null)
4 {
5 System.Runtime.InteropServices.Marshal.ReleaseComObject(WordDoc);
6 WordDoc = null;
7 }
8 WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
9 }
10 catch
11 {
12 try
13 {
14 if (WordApp != null)
15 {
16 System.Runtime.InteropServices.Marshal.ReleaseComObject(WordApp);
17 WordApp = null;
18 }
19 }
20 catch (Exception ex1)
21 {
22 MessageBox.Show(ex1.ToString());
23 }
24
25 }



posted on 2011-11-10 13:45  LuckyLuke  阅读(1045)  评论(0编辑  收藏  举报