c#导出word文档

  为方便下次遇到不知道去哪找先把它存放在这里,以下是保存导出word主要类方法

  1  public class BiultReportForm
  2     {
  3         /// <summary>word 应用对象 </summary>     
  4         private Microsoft.Office.Interop.Word.Application _wordApplication;
  5 
  6         /// <summary>word 文件对象 </summary>    
  7         private Microsoft.Office.Interop.Word.Document _wordDocument;
  8 
  9         /// <summary>
 10         /// 创建word应用对象 
 11         /// </summary>
 12         public void CreateAWord()
 13         {
 14          
 15             //实例化word应用对象    
 16             this._wordApplication = new Microsoft.Office.Interop.Word.Application();
 17         
 18             Object myNothing = System.Reflection.Missing.Value;
 19             this._wordDocument = this._wordApplication.Documents.Add(ref myNothing, ref myNothing, ref myNothing, ref myNothing);
 20         }
 21 
 22        /// <summary>
 23         /// 创建word应用对象 
 24        /// </summary>
 25        /// <param name="strPath">文件目录</param>
 26         public void CreateAWord(string strPath)
 27         {
 28             //判断是否存在目录没有就创建
 29             if (!Directory.Exists(strPath))
 30             {
 31                 Directory.CreateDirectory(strPath);
 32             }
 33             //实例化word应用对象    
 34             this._wordApplication = new Microsoft.Office.Interop.Word.Application(); 
 35             Object myNothing = System.Reflection.Missing.Value;
 36             this._wordDocument = this._wordApplication.Documents.Add(ref myNothing, ref myNothing, ref myNothing, ref myNothing);
 37         }
 38 
 39          /// <summary>
 40         /// 添加页眉
 41          /// </summary>
 42          /// <param name="pPageHeader">标题内容</param>
 43         public void SetPageHeader(string pPageHeader)
 44         {
 45             //添加页眉    
 46             this._wordApplication.ActiveWindow.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdOutlineView;
 47             this._wordApplication.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekPrimaryHeader;
 48             this._wordApplication.ActiveWindow.ActivePane.Selection.InsertAfter(pPageHeader);
 49             //设置中间对齐    
 50             this._wordApplication.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
 51             //跳出页眉设置    
 52             this._wordApplication.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument;
 53         }
 54         
 55         /// <summary>
 56         /// 插入文字
 57         /// </summary>
 58         /// <param name="pText">文本信息</param>
 59         /// <param name="pFontSize">字体打小</param>
 60         /// <param name="pFontColor">字体颜色</param>
 61         /// <param name="pFontBold">字体粗体</param>
 62         /// <param name="ptextAlignment">方向</param>
 63         public void InsertText(string pText, int pFontSize, Microsoft.Office.Interop.Word.WdColor pFontColor, int pFontBold, Microsoft.Office.Interop.Word.WdParagraphAlignment ptextAlignment)
 64         {
 65             //设置字体样式以及方向    
 66             this._wordApplication.Application.Selection.Font.Size = pFontSize;
 67             this._wordApplication.Application.Selection.Font.Bold = pFontBold;
 68             this._wordApplication.Application.Selection.Font.Color = pFontColor;
 69             this._wordApplication.Application.Selection.ParagraphFormat.Alignment = ptextAlignment;
 70             this._wordApplication.Application.Selection.TypeText(pText);
 71         }
 72 
 73         /// <summary>
 74         /// 换行
 75         /// </summary>
 76         public void NewLine()
 77         {
 78             //换行    
 79             this._wordApplication.Application.Selection.TypeParagraph();
 80         }
 81        /// <summary>
 82         /// 插入一个图片
 83        /// </summary>
 84        /// <param name="pPictureFileName">图片名称</param>
 85         public void InsertPicture(string pPictureFileName)
 86         {
 87             object myNothing = System.Reflection.Missing.Value;
 88             //图片居中显示    
 89             this._wordApplication.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
 90             this._wordApplication.Application.Selection.InlineShapes.AddPicture(pPictureFileName, ref myNothing, ref myNothing, ref myNothing);
 91         }
 92 
 93 
 94         /// <summary>
 95         /// 保存文件
 96         /// </summary>
 97         /// <param name="pFileName">传入路径和保存的文件名称</param>
 98         public void SaveWord(string pFileName)
 99         {
100             object myNothing = System.Reflection.Missing.Value;
101             object myFileName = pFileName;
102             object myWordFormatDocument = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;
103             object myLockd = false;
104             object myPassword = "";
105             object myAddto = true;
106             try
107             {
108                 this._wordDocument.SaveAs(ref myFileName, ref myWordFormatDocument, ref myLockd, ref myPassword, ref myAddto, ref myPassword,
109                     ref myLockd, ref myLockd, ref myLockd, ref myLockd, ref myNothing, ref myNothing, ref myNothing,
110                     ref myNothing, ref myNothing, ref myNothing);
111                
112             }
113             catch
114             {
115                 throw new Exception("导出word文档失败!");
116             }
117         }
118 
119         /// <summary>
120         /// 创建目录
121         /// </summary>
122         /// <param name="_directory">目录</param>
123         /// <param name="strPath">地址</param>
124         private void CreatrDirectory(string _directory, string strPath)
125         {
126             //判断是否存在目录没有就创建
127             if (!Directory.Exists(_directory))
128             {
129                 Directory.CreateDirectory(_directory);
130             }
131             //...
132         }
133         /// <summary>
134         /// 获得当前绝对路径
135         /// </summary>
136         /// <param name="strPath">指定的路径</param>
137         /// <returns>绝对路径</returns>
138         public string GetMapPath(string strPath)
139         {
140             if (strPath.ToLower().StartsWith("http://"))
141             {
142                 return strPath;
143             }
144             if (HttpContext.Current != null)
145             {
146                 return HttpContext.Current.Server.MapPath(strPath);
147             }
148             else //非web程序引用
149             {
150                 strPath = strPath.Replace("/", "\\");
151                 if (strPath.StartsWith("\\"))
152                 {
153                     strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\');
154                 }
155                 return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
156             }
157         }
158     
159     }

  前台调用部分

先保证当前文档名称不重复

 1 //时间+随机数
 2         private string chkCodeRequest()
 3         {
 4              
 5             string chkCode = string.Empty;
 6           
 7             //随机的字符集
 8             char[] character = { '2', '3', '4', '5', '6', '8', '9', 'a', 'b', 'd', 'e', 'f', 'h', 'k', 'm', 'n', 'r', 'x', 'y', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
 9             Random rnd = new Random();
10             //字符串 
11             for (int i = 0; i < 4; i++)
12             {
13                 chkCode += character[rnd.Next(character.Length)];
14             }
15             chkCode += DateTime.Now.ToString("yyyyMMddHHmmssffff");
16             return chkCode ;
17         }

保存部分

 1      //写入word与保存
 2         private void SavWord()
 3         {
 4             BiultReportForm word = new BiultReportForm();
 5             string patc = @"f:\测试文件名称\";//目录
 6             word.CreateAWord(patc);//可以带目录参数也可为空
 7             word.SetPageHeader("测试页眉");//设置页面 如果没有就不调用
 8             string str = "dsws";
 9             for (int i = 0; i < 10; i++)
10             {
11                 str += i.ToString();
12                 word.InsertText(str, 12, Microsoft.Office.Interop.Word.WdColor.wdColorBlue, i, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter);//插入内容
13                 word.NewLine();//换行
14             }
15 
16            
17 
18             patc += "测试文件名称";
19             patc += chkCodeRequest();
20             word.SaveWord(patc);
21         }

或者

 1 SaveFileDialog save = new SaveFileDialog();
 2             
 3             //过滤器
 4             save.Filter = "*.doc|*.doc|(*.*)|*.*";
 5 
 6             //显示
 7             if (save.ShowDialog() == DialogResult.OK)
 8             {
 9                 string name = save.FileName;
10                // FileInfo info = new FileInfo(name);
11                 //info.Create();
12                 BiultReportForm word = new BiultReportForm();
13                 word.CreateAWord();
14                 word.SetPageHeader("测试页眉");
15                 string str = "dsws";
16                 for (int i = 0; i < 10; i++)
17                 {
18                     str += i.ToString();
19                     word.InsertText(str, 12, Microsoft.Office.Interop.Word.WdColor.wdColorBlue, i, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter);//插入内容
20                     word.NewLine();//换行
21                 }
22                 word.SaveWord(name);
23                 
24             }

 

 

posted @ 2013-08-19 16:12  继续敷衍、空白的日子  阅读(4061)  评论(1编辑  收藏  举报