最近做的一个项目要求生成Word格式的报告,调试过程中总是出现"服务器出现意外情况。 (异常来自 HRESULT:0x80010105 (RPC_E_SERVERFAULT))"的错误,郁闷了我好几天,最后发现竟然是
WordApp.Documents.Add( ref Nothing, ref Nothing, ref Nothing, ref Visible)
最后一个参数的问题,在此句之前我把Visibale设置成false了,因为我不想在程序生成word文档的时候让用户看见word界面,后来发现即使Visible=true用户也看不到Word界面,
解决方法:Visible=true,能正常运行了,一切OK!
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
5 namespace Business
7 public class WordDocument
8 {
9 Microsoft.Office.Interop.Word.Application WordApp;
10 Microsoft.Office.Interop.Word.Document WordDoc;
11 object SaveChanges = true ;
12 object Visible = true ;// 问题就在这里,改成true后就能正常运行了
13 object Nothing = System.Reflection.Missing.Value;
14 object WordDocPath;
15 public WordDocument( string wordDocPath)
16 {
17 this .WordDocPath = wordDocPath;
18 this .Open();
19 }

20 private void Open()
21 {
22 if (System.IO.File.Exists( this .WordDocPath.ToString()))
23 {
24 System.IO.File.Delete( this .WordDocPath.ToString());
25 }

27 WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
28 WordDoc = WordApp.Documents.Add( ref Nothing, ref Nothing, ref Nothing, ref Visible);
29 }

30 public void Append( string Content, int Level)
31 {
32 WordDoc.Paragraphs.Last.Range.Text = WordDoc.Paragraphs.Last.Range.Text + Content;
33 switch (Level)
34 {
35 case 1 :
36 WordDoc.Paragraphs.Last.Range.Font.Bold = 3 ;
37 WordDoc.Paragraphs.Last.Range.Font.Name = " 宋体 " ;
38 WordDoc.Paragraphs.Last.Range.Font.Size = 16 ;
39 break ;
40 case 2 :
41 WordDoc.Paragraphs.Last.Range.Font.Bold = 3 ;
42 WordDoc.Paragraphs.Last.Range.Font.Name = " 宋体 " ;
43 WordDoc.Paragraphs.Last.Range.Font.Size = 14 ;
44 break ;
45 case 3 :
46 WordDoc.Paragraphs.Last.Range.Font.Bold = 3 ;
47 WordDoc.Paragraphs.Last.Range.Font.Name = " 宋体 " ;
48 WordDoc.Paragraphs.Last.Range.Font.Size = 12 ;
49 // Content = "    " + Content;
50 break ;
51 default :
52 WordDoc.Paragraphs.Last.Range.Font.Bold = 0 ;
53 WordDoc.Paragraphs.Last.Range.Font.Size = 12 ;
54 WordDoc.Paragraphs.Last.Range.Font.Name = " 宋体 " ;
55 // Content = "    " + Content;
56 break ;
57 }

58 // */
60 }

61 public void SaveDoc()
62 {
63 WordDoc.SaveAs( ref this .WordDocPath, ref Nothing, ref Nothing, ref Nothing,
64 ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
65 ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
66 }

67 public void CloseDoc()
68 {
69 WordDoc.Close( ref SaveChanges, ref Nothing, ref Nothing);
70 WordApp.Quit( ref SaveChanges, ref Nothing, ref Nothing);
71 }

72 private void Create( string wordDocPath)
73 {
74 System.IO.FileInfo file = new System.IO.FileInfo(wordDocPath);
75 file.Create();
76 }

77 }