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             }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM