C# 操作word類

1.using System;   
2.using System.Collections.Generic;   
3.using System.Text;   
4.using Microsoft.Office.Interop.Word;   
5.using System.IO;   
6.using System.Web;   
7.using System.Data;   
8.using System.Reflection;   
9.using Microsoft.Win32;   
10.using System.Text.RegularExpressions;   
11.using System.Net;   
12.namespace OfficeOperate   
13.{   
14.    public class WordOperate   
15.    {  
16.        #region 動態生成Word文檔並填充數據   
17.        /**//// <summary>   
18.        /// 動態生成Word文檔並填充數據    
19.        /// </summary>   
20.        /// <returns>返回自定義信息</returns>   
21.        public static string CreateWordFile()   
22.        {   
23.            string message = "";   
24.            try  
25.            {   
26.                Object oMissing = System.Reflection.Missing.Value;   
27.                string dir = System.Web.HttpContext.Current.Server.MapPath( "" );//首先在類庫添加using System.web的引用   
28.                if( !Directory.Exists( dir + "//file" ) )   
29.                {   
30.                    Directory.CreateDirectory( dir + "//file" );  //創建文件所在目錄   
31.                }   
32.                string name = DateTime.Now.ToLongDateString() + ".doc";   
33.                object filename = dir + "//file//" + name;  //文件保存路徑   
34.                //創建Word文檔   
35.                Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();   
36.                Microsoft.Office.Interop.Word.Document WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );   
37.                /**/////添加頁眉方法一:   
38.                //WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView;   
39.                //WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;   
40.                //WordApp.ActiveWindow.ActivePane.Selection.InsertAfter( "無錫全真通科技有限公司" );//頁眉內容   
41.                //添加頁眉方法二:   
42.                if( WordApp.ActiveWindow.ActivePane.View.Type == Microsoft.Office.Interop.Word.WdViewType.wdNormalView || WordApp.ActiveWindow.ActivePane.View.Type == Microsoft.Office.Interop.Word.WdViewType.wdOutlineView )   
43.                {   
44.                    WordApp.ActiveWindow.ActivePane.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdPrintView;   
45.                }   
46.                WordApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageHeader;   
47.                string sHeader = "頁眉內容";   
48.                WordApp.Selection.HeaderFooter.LinkToPrevious = false;   
49.                WordApp.Selection.HeaderFooter.Range.Text = sHeader;   
50.                WordApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument;   
51.  
52.                //WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;//設置右對齊   
53.                WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;//設置左對齊      
54.                WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;//跳出頁眉設置   
55.                WordApp.Selection.ParagraphFormat.LineSpacing = 15f;//設置文檔的行間距   
56.                //移動焦點並換行   
57.                object count = 14;   
58.                object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine;//換一行;   
59.                WordApp.Selection.MoveDown( ref WdLine, ref count, ref oMissing );//移動焦點   
60.                WordApp.Selection.TypeParagraph();//插入段落   
61.                //文檔中創建表格   
62.                Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables.Add( WordApp.Selection.Range, 12, 3, ref oMissing, ref oMissing );   
63.                //設置表格樣式   
64.                newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleThickThinLargeGap;   
65.                newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;   
66.                newTable.Columns[1].Width = 100f;   
67.                newTable.Columns[2].Width = 220f;   
68.                newTable.Columns[3].Width = 105f;   
69.                //填充表格內容   
70.                newTable.Cell( 1, 1 ).Range.Text = "產品詳細信息表";   
71.                newTable.Cell( 1, 1 ).Range.Bold = 2;//設置單元格中字體爲粗體   
72.                //合併單元格   
73.                newTable.Cell( 1, 1 ).Merge( newTable.Cell( 1, 3 ) );   
74.                WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中   
75.                WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中   
76.                //填充表格內容   
77.                newTable.Cell( 2, 1 ).Range.Text = "產品基本信息";   
78.                newTable.Cell( 2, 1 ).Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorDarkBlue;//設置單元格內字體顏色   
79.                //合併單元格   
80.                newTable.Cell( 2, 1 ).Merge( newTable.Cell( 2, 3 ) );   
81.                WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;   
82.                //填充表格內容   
83.                newTable.Cell( 3, 1 ).Range.Text = "品牌名稱:";   
84.                newTable.Cell( 3, 2 ).Range.Text = "BrandName";   
85.                //縱向合併單元格   
86.                newTable.Cell( 3, 3 ).Select();//選中一行   
87.                object moveUnit = Microsoft.Office.Interop.Word.WdUnits.wdLine;   
88.                object moveCount = 5;   
89.                object moveExtend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend;   
90.                WordApp.Selection.MoveDown( ref moveUnit, ref moveCount, ref moveExtend );   
91.                WordApp.Selection.Cells.Merge();   
92.                //插入圖片   
93.                if( File.Exists( System.Web.HttpContext.Current.Server.MapPath( "images//picture.jpg" ) ) )   
94.                {   
95.                    string FileName = System.Web.HttpContext.Current.Server.MapPath( "images//picture.jpg" );//圖片所在路徑   
96.                    object LinkToFile = false;   
97.                    object SaveWithDocument = true;   
98.                    object Anchor = WordDoc.Application.Selection.Range;   
99.                    WordDoc.Application.ActiveDocument.InlineShapes.AddPicture( FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor );   
100.                    WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 100f;//圖片寬度   
101.                    WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f;//圖片高度   
102.                }   
103.                //將圖片設置爲四周環繞型   
104.                Microsoft.Office.Interop.Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();   
105.                s.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare;   
106.                newTable.Cell( 12, 1 ).Range.Text = "產品特殊屬性";   
107.                newTable.Cell( 12, 1 ).Merge( newTable.Cell( 12, 3 ) );   
108.                //在表格中增加行   
109.                WordDoc.Content.Tables[1].Rows.Add( ref oMissing );   
110.                WordDoc.Paragraphs.Last.Range.Text = "文檔創建時間:" + DateTime.Now.ToString();//“落款”   
111.                WordDoc.Paragraphs.Last.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;   
112.                //文件保存   
113.                WordDoc.SaveAs( ref filename, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing );   
114.                WordDoc.Close( ref oMissing, ref oMissing, ref oMissing );   
115.                WordApp.Quit( ref oMissing, ref oMissing, ref oMissing );   
116.                message = name + "文檔生成成功";   
117.            }   
118.            catch  
119.            {   
120.                message = "文件導出異常!";   
121.            }   
122.            return message;   
123.        }  
124.        #endregion         
125.        #region 創建並打開一個空的word文檔進行編輯   
126.        /**//// <summary>   
127.        /// 創建並打開一個空的word文檔進行編輯   
128.        /// </summary>   
129.        public static void OpenNewWordFileToEdit()   
130.        {   
131.            object oMissing = System.Reflection.Missing.Value;   
132.            Microsoft.Office.Interop.Word.Application WordApp;   
133.            Microsoft.Office.Interop.Word.Document WordDoc;   
134.            WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();   
135.            WordApp.Visible = true;   
136.            WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );   
137.        }  
138.        #endregion  
139.        #region 創建word文檔   
140.        /**//// <summary>   
141.        /// 創建word文檔   
142.        /// </summary>   
143.        /// <returns></returns>   
144.        public static string createWord()   
145.        {   
146.            Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();   
147.            Document WordDoc;   
148.            string strContent = "";   
149.            object strFileName = System.Web.HttpContext.Current.Server.MapPath( "test.doc " );   
150.            if( System.IO.File.Exists( (string)strFileName ) )   
151.                System.IO.File.Delete( (string)strFileName );   
152.            Object oMissing = System.Reflection.Missing.Value;   
153.            WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );  
154.            #region   將數據庫中讀取得數據寫入到word文件中   
155.            strContent = "你好/n/n/r ";   
156.            WordDoc.Paragraphs.Last.Range.Text = strContent;   
157.            strContent = "這是測試程序 ";   
158.            WordDoc.Paragraphs.Last.Range.Text = strContent;  
159.            #endregion   
160.            //將WordDoc文檔對象的內容保存爲DOC文檔      
161.            WordDoc.SaveAs( ref strFileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref   oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing );   
162.            //關閉WordDoc文檔對象      
163.            WordDoc.Close( ref oMissing, ref oMissing, ref oMissing );   
164.            //關閉WordApp組件對象      
165.            WordApp.Quit( ref oMissing, ref oMissing, ref oMissing );   
166.            string message = strFileName + "/r/n " + "創建成功 ";   
167.            return message;   
168.        }  
169.        #endregion  
170.        #region 把Word文檔裝化爲Html文件   
171.        /**//// <summary>   
172.        /// 把Word文檔裝化爲Html文件   
173.        /// </summary>   
174.        /// <param name="strFileName">要轉換的Word文檔</param>   
175.        public static void WordToHtml( string strFileName )   
176.        {   
177.            string saveFileName = strFileName + DateTime.Now.ToString( "yyyy-MM-dd-HH-mm-ss" ) + ".html";   
178.            WordToHtml( strFileName, saveFileName );   
179.        }   
180.        /**//// <summary>   
181.        /// 把Word文檔裝化爲Html文件   
182.        /// </summary>   
183.        /// <param name="strFileName">要轉換的Word文檔</param>   
184.        /// <param name="strSaveFileName">要生成的具體的Html頁面</param>   
185.        public static void WordToHtml( string strFileName, string strSaveFileName )   
186.        {   
187.            Microsoft.Office.Interop.Word.ApplicationClass WordApp;    
188.            Microsoft.Office.Interop.Word.Document WordDoc;   
189.            Object oMissing = System.Reflection.Missing.Value;   
190.            WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();   
191.            object fileName = strFileName;   
192.               
193.            WordDoc = WordApp.Documents.Open( ref fileName,   
194.               ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,   
195.               ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,   
196.               ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing );   
197.            Type wordType = WordApp.GetType();   
198.            // 打開文件   
199.            Type docsType = WordApp.Documents.GetType();   
200.            // 轉換格式,另存爲   
201.            Type docType = WordDoc.GetType();   
202.            object saveFileName = strSaveFileName;   
203.            docType.InvokeMember( "SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, WordDoc, new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML } );  
204.            #region 其它格式:   
205.            /**//**/  
206.            /**////wdFormatHTML   
207.            ///wdFormatDocument   
208.            ///wdFormatDOSText   
209.            ///wdFormatDOSTextLineBreaks   
210.            ///wdFormatEncodedText   
211.            ///wdFormatRTF   
212.            ///wdFormatTemplate   
213.            ///wdFormatText   
214.            ///wdFormatTextLineBreaks   
215.            ///wdFormatUnicodeText   
216.            //-----------------------------------------------------------------------------------   
217.            //            docType.InvokeMember( "SaveAs", System.Reflection.BindingFlags.InvokeMethod,   
218.            //                null, WordDoc, new object[]{saveFileName, Word.WdSaveFormat.wdFormatHTML} );   
219.            // 退出 Word   
220.            //wordType.InvokeMember( "Quit", System.Reflection.BindingFlags.InvokeMethod,   
221.            //    null, WordApp, null );  
222.            #endregion   
223.            WordDoc.Close( ref oMissing, ref oMissing, ref oMissing );   
224.            WordApp.Quit( ref oMissing, ref oMissing, ref oMissing );   
225.        }  
226.        #endregion  
227.        #region 導入模板   
228.        /**//// <summary>   
229.        /// 導入模板   
230.        /// </summary>   
231.        /// <param name="filePath">模板文檔路徑</param>   
232.        public static void ImportTemplate( string filePath )   
233.        {   
234.            object oMissing = System.Reflection.Missing.Value;   
235.            Microsoft.Office.Interop.Word.Application WordApp;   
236.            Microsoft.Office.Interop.Word.Document WordDoc;   
237.            WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();   
238.            WordApp.Visible = true;   
239.            object fileName = filePath;   
240.            WordDoc = WordApp.Documents.Add( ref fileName, ref oMissing, ref oMissing, ref oMissing );   
241.        }  
242.        #endregion  
243.        #region word中添加新表   
244.        /**//// <summary>   
245.        /// word中添加新表   
246.        /// </summary>   
247.        public static void AddTable()   
248.        {   
249.            object oMissing = System.Reflection.Missing.Value;   
250.            Microsoft.Office.Interop.Word.Application WordApp;   
251.            Microsoft.Office.Interop.Word.Document WordDoc;   
252.            WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();   
253.            WordApp.Visible = true;   
254.            WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );   
255.            object start = 0;   
256.            object end = 0;   
257.            Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range( ref start, ref end );   
258.            WordDoc.Tables.Add( tableLocation, 3, 4, ref oMissing, ref oMissing );//3行4列的表   
259.        }  
260.        #endregion  
261.        #region 在表中插入新行   
262.        /**//// <summary>   
263.        /// 在表中插入新的1行   
264.        /// </summary>   
265.        public static void AddRow()   
266.        {   
267.            object oMissing = System.Reflection.Missing.Value;   
268.            Microsoft.Office.Interop.Word.Application WordApp;   
269.            Microsoft.Office.Interop.Word.Document WordDoc;   
270.            WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();   
271.            WordApp.Visible = true;   
272.            WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );   
273.            object start = 0;   
274.            object end = 0;   
275.            Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range( ref start, ref end );   
276.            WordDoc.Tables.Add( tableLocation, 3, 4, ref oMissing, ref oMissing );   
277.            Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables[1];   
278.            object beforeRow = newTable.Rows[1];   
279.            newTable.Rows.Add( ref beforeRow );   
280.        }  
281.        #endregion  
282.        #region 分離單元格   
283.        /**//// <summary>   
284.        /// 合併單元格   
285.        /// </summary>   
286.        public static void CombinationCell()   
287.        {   
288.            object oMissing = System.Reflection.Missing.Value;   
289.            Microsoft.Office.Interop.Word.Application WordApp;   
290.            Microsoft.Office.Interop.Word.Document WordDoc;   
291.            WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();   
292.            WordApp.Visible = true;   
293.            WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );   
294.            object start = 0;   
295.            object end = 0;   
296.            Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range( ref start, ref end );   
297.            WordDoc.Tables.Add( tableLocation, 3, 4, ref oMissing, ref oMissing );   
298.            Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables[1];   
299.            object beforeRow = newTable.Rows[1];   
300.            newTable.Rows.Add( ref beforeRow );   
301.            Microsoft.Office.Interop.Word.Cell cell = newTable.Cell( 2, 1 );//2行1列合併2行2列爲一起   
302.            cell.Merge( newTable.Cell( 2, 2 ) );   
303.            //cell.Merge( newTable.Cell( 1, 3 ) );   
304.        }  
305.        #endregion  
306.        #region 分離單元格   
307.        /**//// <summary>   
308.        /// 分離單元格   
309.        /// </summary>   
310.        public static void SeparateCell()   
311.        {   
312.            object oMissing = System.Reflection.Missing.Value;   
313.            Microsoft.Office.Interop.Word.Application WordApp;   
314.            Microsoft.Office.Interop.Word.Document WordDoc;   
315.            WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();   
316.            WordApp.Visible = true;   
317.            WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );   
318.            object start = 0;   
319.            object end = 0;   
320.            Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range( ref start, ref end );   
321.            WordDoc.Tables.Add( tableLocation, 3, 4, ref oMissing, ref oMissing );   
322.            Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables[1];   
323.            object beforeRow = newTable.Rows[1];   
324.            newTable.Rows.Add( ref beforeRow );   
325.            Microsoft.Office.Interop.Word.Cell cell = newTable.Cell( 1, 1 );   
326.            cell.Merge( newTable.Cell( 1, 2 ) );   
327.            object Rownum = 2;   
328.            object Columnnum = 2;   
329.            cell.Split( ref Rownum, ref  Columnnum );   
330.        }  
331.        #endregion  
332. 
333.        #region 通過段落控制插入Insert a paragraph at the beginning of the document.   
334.        /**//// <summary>   
335.        /// 通過段落控制插入Insert a paragraph at the beginning of the document.   
336.        /// </summary>   
337.        public static void Insert()   
338.        {   
339.            object oMissing = System.Reflection.Missing.Value;   
340.            //object oEndOfDoc = "//endofdoc"; /**//* /endofdoc is a predefined bookmark */   
341.            //Start Word and create a new document.   
342.            Microsoft.Office.Interop.Word.Application WordApp;   
343.            Microsoft.Office.Interop.Word.Document WordDoc;   
344.            WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();   
345.            WordApp.Visible = true;   
346.            WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );   
347.            //Insert a paragraph at the beginning of the document.   
348.            Microsoft.Office.Interop.Word.Paragraph oPara1;   
349.            oPara1 = WordDoc.Content.Paragraphs.Add( ref oMissing );   
350.            oPara1.Range.Text = "Heading 1";   
351.            oPara1.Range.Font.Bold = 1;   
352.            oPara1.Format.SpaceAfter = 24;    //24 pt spacing after paragraph.   
353.            oPara1.Range.InsertParagraphAfter();   
354.        }  
355.        #endregion  
356. 
357.        #region word文檔設置及獲取光標位置   
358.        /**//// <summary>   
359.        /// word文檔設置及獲取光標位置   
360.        /// </summary>   
361.        public static void WordSet()   
362.        {   
363.            object oMissing = System.Reflection.Missing.Value;   
364.            Microsoft.Office.Interop.Word.Application WordApp;   
365.            Microsoft.Office.Interop.Word.Document WordDoc;   
366.            WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();  
367.            #region 文檔格式設置   
368.            WordApp.ActiveDocument.PageSetup.LineNumbering.Active = 0;//行編號   
369.            WordApp.ActiveDocument.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientPortrait;//頁面方向   
370.            WordApp.ActiveDocument.PageSetup.TopMargin = WordApp.CentimetersToPoints( float.Parse( "2.54" ) );//上頁邊距   
371.            WordApp.ActiveDocument.PageSetup.BottomMargin = WordApp.CentimetersToPoints( float.Parse( "2.54" ) );//下頁邊距   
372.            WordApp.ActiveDocument.PageSetup.LeftMargin = WordApp.CentimetersToPoints( float.Parse( "3.17" ) );//左頁邊距   
373.            WordApp.ActiveDocument.PageSetup.RightMargin = WordApp.CentimetersToPoints( float.Parse( "3.17" ) );//右頁邊距   
374.            WordApp.ActiveDocument.PageSetup.Gutter = WordApp.CentimetersToPoints( float.Parse( "0" ) );//裝訂線位置   
375.            WordApp.ActiveDocument.PageSetup.HeaderDistance = WordApp.CentimetersToPoints( float.Parse( "1.5" ) );//頁眉   
376.            WordApp.ActiveDocument.PageSetup.FooterDistance = WordApp.CentimetersToPoints( float.Parse( "1.75" ) );//頁腳   
377.            WordApp.ActiveDocument.PageSetup.PageWidth = WordApp.CentimetersToPoints( float.Parse( "21" ) );//紙張寬度   
378.            WordApp.ActiveDocument.PageSetup.PageHeight = WordApp.CentimetersToPoints( float.Parse( "29.7" ) );//紙張高度   
379.            WordApp.ActiveDocument.PageSetup.FirstPageTray = Microsoft.Office.Interop.Word.WdPaperTray.wdPrinterDefaultBin;//紙張來源   
380.            WordApp.ActiveDocument.PageSetup.OtherPagesTray = Microsoft.Office.Interop.Word.WdPaperTray.wdPrinterDefaultBin;//紙張來源   
381.            WordApp.ActiveDocument.PageSetup.SectionStart = Microsoft.Office.Interop.Word.WdSectionStart.wdSectionNewPage;//節的起始位置:新建頁   
382.            WordApp.ActiveDocument.PageSetup.OddAndEvenPagesHeaderFooter = 0;//頁眉頁腳-奇偶頁不同   
383.            WordApp.ActiveDocument.PageSetup.DifferentFirstPageHeaderFooter = 0;//頁眉頁腳-首頁不同   
384.            WordApp.ActiveDocument.PageSetup.VerticalAlignment = Microsoft.Office.Interop.Word.WdVerticalAlignment.wdAlignVerticalTop;//頁面垂直對齊方式   
385.            WordApp.ActiveDocument.PageSetup.SuppressEndnotes = 0;//不隱藏尾註   
386.            WordApp.ActiveDocument.PageSetup.MirrorMargins = 0;//不設置首頁的內外邊距   
387.            WordApp.ActiveDocument.PageSetup.TwoPagesOnOne = false;//不雙面打印   
388.            WordApp.ActiveDocument.PageSetup.BookFoldPrinting = false;//不設置手動雙面正面打印   
389.            WordApp.ActiveDocument.PageSetup.BookFoldRevPrinting = false;//不設置手動雙面背面打印   
390.            WordApp.ActiveDocument.PageSetup.BookFoldPrintingSheets = 1;//打印默認份數   
391.            WordApp.ActiveDocument.PageSetup.GutterPos = Microsoft.Office.Interop.Word.WdGutterStyle.wdGutterPosLeft;//裝訂線位於左側   
392.            WordApp.ActiveDocument.PageSetup.LinesPage = 40;//默認頁行數量   
393.            WordApp.ActiveDocument.PageSetup.LayoutMode = Microsoft.Office.Interop.Word.WdLayoutMode.wdLayoutModeLineGrid;//版式模式爲“只指定行網格”  
394.            #endregion  
395.            #region 段落格式設定   
396.            WordApp.Selection.ParagraphFormat.LeftIndent = WordApp.CentimetersToPoints( float.Parse( "0" ) );//左縮進   
397.            WordApp.Selection.ParagraphFormat.RightIndent = WordApp.CentimetersToPoints( float.Parse( "0" ) );//右縮進   
398.            WordApp.Selection.ParagraphFormat.SpaceBefore = float.Parse( "0" );//段前間距   
399.            WordApp.Selection.ParagraphFormat.SpaceBeforeAuto = 0;//   
400.            WordApp.Selection.ParagraphFormat.SpaceAfter = float.Parse( "0" );//段後間距   
401.            WordApp.Selection.ParagraphFormat.SpaceAfterAuto = 0;//   
402.            WordApp.Selection.ParagraphFormat.LineSpacingRule = Microsoft.Office.Interop.Word.WdLineSpacing.wdLineSpaceSingle;//單倍行距   
403.            WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;//段落2端對齊   
404.            WordApp.Selection.ParagraphFormat.WidowControl = 0;//孤行控制   
405.            WordApp.Selection.ParagraphFormat.KeepWithNext = 0;//與下段同頁   
406.            WordApp.Selection.ParagraphFormat.KeepTogether = 0;//段中不分頁   
407.            WordApp.Selection.ParagraphFormat.PageBreakBefore = 0;//段前分頁   
408.            WordApp.Selection.ParagraphFormat.NoLineNumber = 0;//取消行號   
409.            WordApp.Selection.ParagraphFormat.Hyphenation = 1;//取消段字   
410.            WordApp.Selection.ParagraphFormat.FirstLineIndent = WordApp.CentimetersToPoints( float.Parse( "0" ) );//首行縮進   
411.            WordApp.Selection.ParagraphFormat.OutlineLevel = Microsoft.Office.Interop.Word.WdOutlineLevel.wdOutlineLevelBodyText;   
412.            WordApp.Selection.ParagraphFormat.CharacterUnitLeftIndent = float.Parse( "0" );   
413.            WordApp.Selection.ParagraphFormat.CharacterUnitRightIndent = float.Parse( "0" );   
414.            WordApp.Selection.ParagraphFormat.CharacterUnitFirstLineIndent = float.Parse( "0" );   
415.            WordApp.Selection.ParagraphFormat.LineUnitBefore = float.Parse( "0" );   
416.            WordApp.Selection.ParagraphFormat.LineUnitAfter = float.Parse( "0" );   
417.            WordApp.Selection.ParagraphFormat.AutoAdjustRightIndent = 1;   
418.            WordApp.Selection.ParagraphFormat.DisableLineHeightGrid = 0;   
419.            WordApp.Selection.ParagraphFormat.FarEastLineBreakControl = 1;   
420.            WordApp.Selection.ParagraphFormat.WordWrap = 1;   
421.            WordApp.Selection.ParagraphFormat.HangingPunctuation = 1;   
422.            WordApp.Selection.ParagraphFormat.HalfWidthPunctuationOnTopOfLine = 0;   
423.            WordApp.Selection.ParagraphFormat.AddSpaceBetweenFarEastAndAlpha = 1;   
424.            WordApp.Selection.ParagraphFormat.AddSpaceBetweenFarEastAndDigit = 1;   
425.            WordApp.Selection.ParagraphFormat.BaseLineAlignment = Microsoft.Office.Interop.Word.WdBaselineAlignment.wdBaselineAlignAuto;  
426.            #endregion  
427.            #region 字體格式設定   
428.            WordApp.Selection.Font.NameFarEast = "華文中宋";   
429.            WordApp.Selection.Font.NameAscii = "Times New Roman";   
430.            WordApp.Selection.Font.NameOther = "Times New Roman";   
431.            WordApp.Selection.Font.Name = "宋體";   
432.            WordApp.Selection.Font.Size = float.Parse( "14" );   
433.            WordApp.Selection.Font.Bold = 0;   
434.            WordApp.Selection.Font.Italic = 0;   
435.            WordApp.Selection.Font.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineNone;   
436.            WordApp.Selection.Font.UnderlineColor = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic;   
437.            WordApp.Selection.Font.StrikeThrough = 0;//刪除線   
438.            WordApp.Selection.Font.DoubleStrikeThrough = 0;//雙刪除線   
439.            WordApp.Selection.Font.Outline = 0;//空心   
440.            WordApp.Selection.Font.Emboss = 0;//陽文   
441.            WordApp.Selection.Font.Shadow = 0;//陰影   
442.            WordApp.Selection.Font.Hidden = 0;//隱藏文字   
443.            WordApp.Selection.Font.SmallCaps = 0;//小型大寫字母   
444.            WordApp.Selection.Font.AllCaps = 0;//全部大寫字母   
445.            WordApp.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic;   
446.            WordApp.Selection.Font.Engrave = 0;//陰文   
447.            WordApp.Selection.Font.Superscript = 0;//上標   
448.            WordApp.Selection.Font.Subscript = 0;//下標   
449.            WordApp.Selection.Font.Spacing = float.Parse( "0" );//字符間距   
450.            WordApp.Selection.Font.Scaling = 100;//字符縮放   
451.            WordApp.Selection.Font.Position = 0;//位置   
452.            WordApp.Selection.Font.Kerning = float.Parse( "1" );//字體間距調整   
453.            WordApp.Selection.Font.Animation = Microsoft.Office.Interop.Word.WdAnimation.wdAnimationNone;//文字效果   
454.            WordApp.Selection.Font.DisableCharacterSpaceGrid = false;   
455.            WordApp.Selection.Font.EmphasisMark = Microsoft.Office.Interop.Word.WdEmphasisMark.wdEmphasisMarkNone;  
456.            #endregion  
457.            #region 獲取光標位置   
458.            /**/////get_Information   
459.            WordApp.Selection.get_Information( WdInformation.wdActiveEndPageNumber );   
460.            //關於行號-頁號-列號-位置   
461.            //information 屬性    
462.            //返回有關指定的所選內容或區域的信息。variant 類型,只讀。    
463.            //expression.information(type)    
464.            //expression 必需。該表達式返回一個 range 或 selection 對象。    
465.            //type long 類型,必需。需要返回的信息。可取下列 wdinformation 常量之一:    
466.            //wdactiveendadjustedpagenumber 返回頁碼,在該頁中包含指定的所選內容或區域的活動結尾。如果設置了一個起始頁碼,並對頁碼進行了手工調整,則返回調整過的頁碼。    
467.            //wdactiveendpagenumber 返回頁碼,在該頁中包含指定的所選內容或區域的活動結尾,頁碼從文檔的開頭開始計算而不考慮對頁碼的任何手工調整。    
468.            //wdactiveendsectionnumber 返回節號,在該節中包含了指定的所選內容或區域的活動結尾。    
469.            //wdatendofrowmarker 如果指定的所選內容或區域位於表格的行結尾標記處,則本參數返回 true。    
470.            //wdcapslock 如果大寫字母鎖定模式有效,則本參數返回 true。    
471.            //wdendofrangecolumnnumber 返回表格列號,在該表格列中包含了指定的所選內容或區域的活動結尾。    
472.            //wdendofrangerownumber 返回表格行號,在該表格行包含了指定的所選內容或區域的活動結尾。    
473.            //wdfirstcharactercolumnnumber 返回指定的所選內容或區域中第一個字符的位置。如果所選內容或區域是摺疊的,則返回所選內容或區域右側緊接着的字符編號。    
474.            //wdfirstcharacterlinenumber 返回所選內容中第一個字符的行號。如果 pagination 屬性爲 false,或 draft 屬性爲 true,則返回 - 1。    
475.            //wdframeisselected 如果所選內容或區域是一個完整的圖文框文本框,則本參數返回 true。    
476.            //wdheaderfootertype 返回一個值,該值表明包含了指定的所選內容或區域的頁眉或頁腳的類型,如下表所示。 值 頁眉或頁腳的類型    
477.            //- 1 無    
478.            //0 偶數頁頁眉    
479.            //1 奇數頁頁眉    
480.            //2 偶數頁頁腳    
481.            //3 奇數頁頁腳    
482.            //4 第一個頁眉    
483.            //5 第一個頁腳    
484.            //wdhorizontalpositionrelativetopage 返回指定的所選內容或區域的水平位置。該位置是所選內容或區域的左邊與頁面的左邊之間的距離,以磅爲單位。如果所選內容或區域不可見,則返回 - 1。    
485.            //wdhorizontalpositionrelativetotextboundary 返回指定的所選內容或區域相對於周圍最近的正文邊界的左邊的水平位置,以磅爲單位。如果所選內容或區域沒有顯示在當前屏幕,則本參數返回 - 1。    
486.            //wdinclipboard 有關此常量的詳細內容,請參閱 microsoft office 98 macintosh 版的語言參考幫助。    
487.            //wdincommentpane 如果指定的所選內容或區域位於批註窗格,則返回 true。    
488.            //wdinendnote 如果指定的所選內容或區域位於頁面視圖的尾註區內,或者位於普通視圖的尾註窗格中,則本參數返回 true。    
489.            //wdinfootnote 如果指定的所選內容或區域位於頁面視圖的腳註區內,或者位於普通視圖的腳註窗格中,則本參數返回 true。    
490.            //wdinfootnoteendnotepane 如果指定的所選內容或區域位於頁面視圖的腳註或尾註區內,或者位於普通視圖的腳註或尾註窗格中,則本參數返回 true。詳細內容,請參閱前面的 wdinfootnote 和 wdinendnote 的說明。    
491.            //wdinheaderfooter 如果指定的所選內容或區域位於頁眉或頁腳窗格中,或者位於頁面視圖的頁眉或頁腳中,則本參數返回 true。    
492.            //wdinmasterdocument 如果指定的所選內容或區域位於主控文檔中,則本參數返回 true。    
493.            //wdinwordmail 返回一個值,該值表明了所選內容或區域的的位置,如下表所示。值 位置    
494.            //0 所選內容或區域不在一條電子郵件消息中。    
495.            //1 所選內容或區域位於正在發送的電子郵件中。    
496.            //2 所選內容或區域位於正在閱讀的電子郵件中。    
497.            //wdmaximumnumberofcolumns 返回所選內容或區域中任何行的最大表格列數。    
498.            //wdmaximumnumberofrows 返回指定的所選內容或區域中表格的最大行數。    
499.            //wdnumberofpagesindocument 返回與所選內容或區域相關聯的文檔的頁數。    
500.            //wdnumlock 如果 num lock 有效,則本參數返回 true。    
501.            //wdovertype 如果改寫模式有效,則本參數返回 true。可用 overtype 屬性改變改寫模式的狀態。    
502.            //wdreferenceoftype 返回一個值,該值表明所選內容相對於腳註、尾註或批註引用的位置,如下表所示。 值 描述    
503.            //— 1 所選內容或區域包含、但不只限定於腳註、尾註或批註引用中。    
504.            //0 所選內容或區域不在腳註、尾註或批註引用之前。    
505.            //1 所選內容或區域位於腳註引用之前。    
506.            //2 所選內容或區域位於尾註引用之前。    
507.            //3 所選內容或區域位於批註引用之前。    
508.            //wdrevisionmarking 如果修訂功能處於活動狀態,則本參數返回 true。    
509.            //wdselectionmode 返回一個值,該值表明當前的選定模式,如下表所示。 值 選定模式    
510.            //0 常規選定    
511.            //1 擴展選定    
512.            //2 列選定    
513.            //wdstartofrangecolumnnumber 返回所選內容或區域的起點所在的表格的列號。    
514.            //wdstartofrangerownumber 返回所選內容或區域的起點所在的表格的行號。    
515.            //wdverticalpositionrelativetopage 返回所選內容或區域的垂直位置,即所選內容的上邊與頁面的上邊之間的距離,以磅爲單位。如果所選內容或區域沒有顯示在屏幕上,則本參數返回 - 1。    
516.            //wdverticalpositionrelativetotextboundary 返回所選內容或區域相對於周圍最近的正文邊界的上邊的垂直位置,以磅爲單位。如果所選內容或區域沒有顯示在屏幕上,則本參數返回 - 1。    
517.            //wdwithintable 如果所選內容位於一個表格中,則本參數返回 true。    
518.            //wdzoompercentage 返回由 percentage 屬性設置的當前的放大百分比。  
519.            #endregion  
520.            #region 光標移動   
521.            //移動光標   
522.            //光標下移3行 上移3行   
523.            object unit = Microsoft.Office.Interop.Word.WdUnits.wdLine;   
524.            object count = 3;   
525.            WordApp.Selection.MoveEnd( ref unit, ref count );   
526.            WordApp.Selection.MoveUp( ref unit, ref count, ref oMissing );   
527.            //Microsoft.Office.Interop.Word.WdUnits說明   
528.            //wdCell                  A cell.    
529.            //wdCharacter             A character.    
530.            //wdCharacterFormatting   Character formatting.    
531.            //wdColumn                A column.    
532.            //wdItem                  The selected item.    
533.            //wdLine                  A line. //行   
534.            //wdParagraph             A paragraph.    
535.            //wdParagraphFormatting   Paragraph formatting.    
536.            //wdRow                   A row.    
537.            //wdScreen                The screen dimensions.    
538.            //wdSection               A section.    
539.            //wdSentence              A sentence.    
540.            //wdStory                 A story.    
541.            //wdTable                 A table.    
542.            //wdWindow                A window.    
543.            //wdWord                  A word.   
544.            //錄製的vb宏   
545.            //     ,移動光標至當前行首   
546.            //    Selection.HomeKey unit:=wdLine   
547.            //    '移動光標至當前行尾   
548.            //    Selection.EndKey unit:=wdLine   
549.            //    '選擇從光標至當前行首的內容   
550.            //    Selection.HomeKey unit:=wdLine, Extend:=wdExtend   
551.            //    '選擇從光標至當前行尾的內容   
552.            //    Selection.EndKey unit:=wdLine, Extend:=wdExtend   
553.            //    '選擇當前行   
554.            //    Selection.HomeKey unit:=wdLine   
555.            //    Selection.EndKey unit:=wdLine, Extend:=wdExtend   
556.            //    '移動光標至文檔開始   
557.            //    Selection.HomeKey unit:=wdStory   
558.            //    '移動光標至文檔結尾   
559.            //    Selection.EndKey unit:=wdStory   
560.            //    '選擇從光標至文檔開始的內容   
561.            //    Selection.HomeKey unit:=wdStory, Extend:=wdExtend   
562.            //    '選擇從光標至文檔結尾的內容   
563.            //    Selection.EndKey unit:=wdStory, Extend:=wdExtend   
564.            //    '選擇文檔全部內容(從WholeStory可猜出Story應是當前文檔的意思)   
565.            //    Selection.WholeStory   
566.            //    '移動光標至當前段落的開始   
567.            //    Selection.MoveUp unit:=wdParagraph   
568.            //    '移動光標至當前段落的結尾   
569.            //    Selection.MoveDown unit:=wdParagraph   
570.            //    '選擇從光標至當前段落開始的內容   
571.            //    Selection.MoveUp unit:=wdParagraph, Extend:=wdExtend   
572.            //    '選擇從光標至當前段落結尾的內容   
573.            //    Selection.MoveDown unit:=wdParagraph, Extend:=wdExtend   
574.            //    '選擇光標所在段落的內容   
575.            //    Selection.MoveUp unit:=wdParagraph   
576.            //    Selection.MoveDown unit:=wdParagraph, Extend:=wdExtend   
577.            //    '顯示選擇區的開始與結束的位置,注意:文檔第1個字符的位置是0   
578.            //    MsgBox ("第" & Selection.Start & "個字符至第" & Selection.End & "個字符")   
579.            //    '刪除當前行   
580.            //    Selection.HomeKey unit:=wdLine   
581.            //    Selection.EndKey unit:=wdLine, Extend:=wdExtend   
582.            //    Selection.Delete   
583.            //    '刪除當前段落   
584.            //    Selection.MoveUp unit:=wdParagraph   
585.            //    Selection.MoveDown unit:=wdParagraph, Extend:=wdExtend   
586.            //    Selection.Delete   
587.  
588.            //表格的光標移動   
589.            //光標到當前光標所在表格的地單元格   
590.            WordApp.Selection.Tables[1].Cell( 1, 1 ).Select();   
591.            //unit對象定義   
592.            object unith = Microsoft.Office.Interop.Word.WdUnits.wdRow;//表格行方式   
593.            object extend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend;/**//**//**////extend對光標移動區域進行擴展選擇   
594.            object unitu = Microsoft.Office.Interop.Word.WdUnits.wdLine;//文檔行方式,可以看成表格一行.不過和wdRow有區別   
595.            object unitp = Microsoft.Office.Interop.Word.WdUnits.wdParagraph;//段落方式,對於表格可以選擇到表格行後的換車符,對於跨行合併的行選擇,我能找到的最簡單方式   
596.            //object count = 1;//光標移動量  
597.            #endregion   
598.        }  
599.        #endregion  
600. 
601.        #region 讀取Word表格中某個單元格的數據。其中的參數分別爲文件名(包括路徑),行號,列號。   
602.        /**//// <summary>   
603.        /// 讀取Word表格中某個單元格的數據。其中的參數分別爲文件名(包括路徑),行號,列號。   
604.        /// </summary>   
605.        /// <param name="fileName">word文檔</param>   
606.        /// <param name="rowIndex">行</param>   
607.        /// <param name="colIndex">列</param>   
608.        /// <returns>返回數據</returns>   
609.        public static string ReadWord_tableContentByCell( string fileName, int rowIndex, int colIndex )   
610.        {   
611.            ApplicationClass cls = null;   
612.            Document doc = null;   
613.            Table table = null;   
614.            object missing = Missing.Value;   
615.            object path = fileName;   
616.            cls = new ApplicationClass();   
617.            try  
618.            {   
619.                doc = cls.Documents.Open   
620.                  ( ref path, ref missing, ref missing, ref missing,   
621.                  ref missing, ref missing, ref missing, ref missing,   
622.                  ref missing, ref missing, ref missing, ref missing,   
623.                  ref missing, ref missing, ref missing, ref missing );   
624.                table = doc.Tables[1];   
625.                string text = table.Cell( rowIndex, colIndex ).Range.Text.ToString();   
626.                text = text.Substring( 0, text.Length - 2 );  //去除尾部的mark   
627.                return text;   
628.            }   
629.            catch( Exception ex )   
630.            {   
631.                return ex.Message;   
632.            }   
633.            finally  
634.            {   
635.                if( doc != null )   
636.                    doc.Close( ref missing, ref missing, ref missing );   
637.                cls.Quit( ref missing, ref missing, ref missing );   
638.            }   
639.        }  
640.        #endregion  
641.          
642.        #region 修改word表格中指定單元格的數據   
643.        /**//// <summary>   
644.        /// 修改word表格中指定單元格的數據   
645.        /// </summary>   
646.        /// <param name="fileName">word文檔包括路徑</param>   
647.        /// <param name="rowIndex">行</param>   
648.        /// <param name="colIndex">列</param>   
649.        /// <param name="content"></param>   
650.        /// <returns></returns>   
651.        public static bool UpdateWordTableByCell( string fileName, int rowIndex, int colIndex, string content )   
652.        {   
653.            ApplicationClass cls = null;   
654.            Document doc = null;   
655.            Table table = null;   
656.            object missing = Missing.Value;   
657.            object path = fileName;   
658.            cls = new ApplicationClass();   
659.            try  
660.            {   
661.                doc = cls.Documents.Open   
662.                    ( ref path, ref missing, ref missing, ref missing,   
663.                  ref missing, ref missing, ref missing, ref missing,   
664.                  ref missing, ref missing, ref missing, ref missing,   
665.                  ref missing, ref missing, ref missing, ref missing );   
666.                table = doc.Tables[1];   
667.                //doc.Range( ref 0, ref 0 ).InsertParagraphAfter();//插入回車   
668.                table.Cell( rowIndex, colIndex ).Range.InsertParagraphAfter();//.Text = content;   
669.                return true;   
670.            }   
671.            catch  
672.            {   
673.                return false;   
674.            }   
675.            finally  
676.            {   
677.                if( doc != null )   
678.                {   
679.                    doc.Close( ref missing, ref missing, ref missing );   
680.                    cls.Quit( ref missing, ref missing, ref missing );   
681.                }   
682.            }   
683.        }  
684.        #endregion   
685.          
686.        #region 清楚word進程   
687.        /**//// <summary>   
688.        /// 清楚word進程   
689.        /// </summary>   
690.        public static void KillWordProcess()   
691.        {   
692.            System.Diagnostics.Process[] myPs;   
693.            myPs = System.Diagnostics.Process.GetProcesses();   
694.            foreach( System.Diagnostics.Process p in myPs )   
695.            {   
696.                if( p.Id != 0 )   
697.                {   
698.                    string myS = "WINWORD.EXE" + p.ProcessName + "  ID:" + p.Id.ToString();   
699.                    try  
700.                    {   
701.                        if( p.Modules != null )   
702.                            if( p.Modules.Count > 0 )   
703.                            {   
704.                                System.Diagnostics.ProcessModule pm = p.Modules[0];   
705.                                myS += "/n Modules[0].FileName:" + pm.FileName;   
706.                                myS += "/n Modules[0].ModuleName:" + pm.ModuleName;   
707.                                myS += "/n Modules[0].FileVersionInfo:/n" + pm.FileVersionInfo.ToString();   
708.                                if( pm.ModuleName.ToLower() == "winword.exe" )   
709.                                    p.Kill();   
710.                            }   
711.                    }   
712.                    catch  
713.                    { }   
714.                    finally  
715.                    {   
716.                        ;   
717.                    }   
718.                }   
719.            }   
720.        }  
721.        #endregion   
722.          
723.        #region 清楚excel進程   
724.        /**//// <summary>   
725.        /// 清楚excel進程   
726.        /// </summary>   
727.        public static void KillExcelProcess()   
728.        {   
729.            System.Diagnostics.Process[] myPs;   
730.            myPs = System.Diagnostics.Process.GetProcesses();   
731.            foreach( System.Diagnostics.Process p in myPs )   
732.            {   
733.                if( p.Id != 0 )   
734.                {   
735.                    string myS = "excel.EXE" + p.ProcessName + "  ID:" + p.Id.ToString();   
736.                    try  
737.                    {   
738.                        if( p.Modules != null )   
739.                            if( p.Modules.Count > 0 )   
740.                            {   
741.                                System.Diagnostics.ProcessModule pm = p.Modules[0];   
742.                                myS += "/n Modules[0].FileName:" + pm.FileName;   
743.                                myS += "/n Modules[0].ModuleName:" + pm.ModuleName;   
744.                                myS += "/n Modules[0].FileVersionInfo:/n" + pm.FileVersionInfo.ToString();   
745.                                if( pm.ModuleName.ToLower() == "excel.exe" )   
746.                                    p.Kill();   
747.                            }   
748.                    }   
749.                    catch  
750.                    { }   
751.                    finally  
752.                    {   
753.                        ;   
754.                    }   
755.                }   
756.            }   
757.        }  
758.        #endregion   
759.          
760.        #region 網頁內容或導入word或excel   
761.        /**//// <summary>   
762.        /// 網頁內容保存或導出爲word或excel   
763.        /// </summary>   
764.        /// <param name="url">網頁地址</param>   
765.        /// <param name="num">0爲導出word,1爲導出excel</param>   
766.        public static void SaveOrOutData( string url, int num )//導出數據的函數0爲word,1爲Excel    
767.        {   
768.            WebRequest req = WebRequest.Create( url );   
769.            WebResponse resp = req.GetResponse();   
770.            StreamReader sr = new StreamReader( resp.GetResponseStream(), System.Text.Encoding.UTF8 );   
771.            string x = sr.ReadToEnd();   
772.            System.Web.HttpContext.Current.Response.Clear();   
773.            System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding( "gb2312" );   
774.            string fName = DateTime.Now.ToString( "yyyy-MM-dd-ss" );   
775.            if( num == 0 )   
776.            {   
777.                fName = HttpUtility.UrlEncode( fName, System.Text.Encoding.GetEncoding( "gb2312" ) ) + ".doc";   
778.                System.Web.HttpContext.Current.Response.ContentType = "application/ms-word";   
779.            }   
780.            else  
781.            {   
782.                fName = HttpUtility.UrlEncode( fName, System.Text.Encoding.GetEncoding( "gb2312" ) ) + ".xls";   
783.                System.Web.HttpContext.Current.Response.ContentType = "application nd.xls";   
784.            }   
785.            System.Web.HttpContext.Current.Response.AddHeader( "content-disposition", "attachment;filename=" + fName );   
786.            System.Web.HttpContext.Current.Response.Write( getBodyContent( x ) );//獲取table標籤   
787.            System.Web.HttpContext.Current.Response.Flush();   
788.            System.Web.HttpContext.Current.Response.End();   
789.        }   
790.        /**//// <summary>   
791.        /// 獲取網頁table標籤的內容   
792.        /// </summary>   
793.        /// <param name="input">html代碼</param>   
794.        /// <returns></returns>   
795.        private static string getBodyContent( string input )   
796.        {   
797.            string pattern = @"<table.*?</table>";   
798.            Regex reg = new Regex( pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase );   
799.            Match mc = reg.Match( input );   
800.            string bodyContent = "";   
801.            if( mc.Success )   
802.            {   
803.                bodyContent = mc.Value;   
804.            }   
805.            return bodyContent;   
806.        }  
807.        #endregion    
808.          
809.        #region 判斷系統是否裝excel   
810.        /**//// <summary>   
811.        /// 判斷系統是否裝excel   
812.        /// </summary>   
813.        /// <returns></returns>   
814.        public static bool IsInstallExcel()   
815.        {   
816.            RegistryKey machineKey = Registry.LocalMachine;   
817.            if( IsInstallExcelByVersion( "12.0", machineKey ) )   
818.            {   
819.                return true;   
820.            }   
821.            if( IsInstallExcelByVersion( "11.0", machineKey ) )   
822.            {   
823.                return true;   
824.            }   
825.            return false;   
826.        }   
827.        /**//// <summary>   
828.        /// 判斷系統是否裝某版本的excel   
829.        /// </summary>   
830.        /// <param name="strVersion">版本號</param>   
831.        /// <param name="machineKey"></param>   
832.        /// <returns></returns>   
833.        private static bool IsInstallExcelByVersion( string strVersion, RegistryKey machineKey )   
834.        {   
835.            try  
836.            {   
837.                RegistryKey installKey = machineKey.OpenSubKey( "Software" ).OpenSubKey( "Microsoft" ).OpenSubKey( "Office" ).OpenSubKey( strVersion ).OpenSubKey( "Excel" ).OpenSubKey( "InstallRoot" );   
838.                if( installKey == null )   
839.                {   
840.                    return false;   
841.                }   
842.                return true;   
843.            }   
844.            catch  
845.            {   
846.                return false;   
847.            }   
848.        }  
849.        #endregion   
850.          
851.        #region 判斷系統是否裝word   
852.        /**//// <summary>   
853.        /// 判斷系統是否裝word   
854.        /// </summary>   
855.        /// <returns></returns>   
856.        public static bool IsInstallWord()   
857.        {   
858.            RegistryKey machineKey = Registry.LocalMachine;   
859.            if( IsInstallExcelByVersion( "12.0", machineKey ) )   
860.            {   
861.                return true;   
862.            }   
863.            if( IsInstallExcelByVersion( "11.0", machineKey ) )   
864.            {   
865.                return true;   
866.            }   
867.            return false;   
868.        }   
869.        /**//// <summary>   
870.        /// 判斷系統是否裝某版本的word   
871.        /// </summary>   
872.        /// <param name="strVersion">版本號</param>   
873.        /// <param name="machineKey"></param>   
874.        /// <returns></returns>   
875.        private static bool IsInstallWordByVersion( string strVersion, RegistryKey machineKey )   
876.        {   
877.            try  
878.            {   
879.                RegistryKey installKey = machineKey.OpenSubKey( "Software" ).OpenSubKey( "Microsoft" ).OpenSubKey( "Office" ).OpenSubKey( strVersion ).OpenSubKey( "Word" ).OpenSubKey( "InstallRoot" );   
880.                if( installKey == null )   
881.                {   
882.                    return false;   
883.                }   
884.                return true;   
885.            }   
886.            catch  
887.            {   
888.                return false;   
889.            }   
890.        }  
891.        #endregion                  
892.    }   
893.}  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章