C# 操作word 類

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Word = Microsoft.Office.Interop.Word;
namespace bookmark
{
    class WordHelper
    {
        private Word.Document wDoc = null;
        private Word.Application wApp = null;

        public Word.Document Document
        {
            get { return wDoc; }
            set { wDoc = value; }
        }

        public Word.Application Application
        {
            get { return wApp; }
            set { wApp = value; }
        }


        #region 從模板創建新的Word文檔
        /// <summary>   
        /// 從模板創建新的Word文檔   
        /// </summary>   
        /// <param name="templateName">模板文件名</param>   
        /// <returns></returns>  
        public bool CreateNewWordDocument(string templateName)
        {
            try
            {
                return CreateNewWordDocument(templateName, ref wDoc, ref wApp);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion



        #region 從模板創建新的Word文檔,並且返回對象Document,Application
        /// <summary>   
        /// 從模板創建新的Word文檔,   
        /// </summary>   
        /// <param name="templateName">模板文件名</param>   
        /// <param name="wDoc">返回的Word.Document對象</param>   
        /// <param name="WApp">返回的Word.Application對象</param>   
        /// <returns></returns>  
        public static bool CreateNewWordDocument(string templateName, ref Word.Document wDoc, ref Word.Application WApp)
        {
            killWinWordProcess();
            Word.Document thisDocument = null;
            Word.Application thisApplication = new Word.ApplicationClass();
            thisApplication.Visible = false;
            thisApplication.Caption = "";  //標題
            thisApplication.Options.CheckSpellingAsYouType = false;
            thisApplication.Options.CheckGrammarAsYouType = false;

            Object Template = templateName;// Optional Object. The name of the template to be used for the new document. If this argument is omitted, the Normal template is used.

            Object NewTemplate = false;// Optional Object. True to open the document as a template. The default value is False.

            Object DocumentType = Word.WdNewDocumentType.wdNewBlankDocument; // Optional Object. Can be one of the following WdNewDocumentType constants: wdNewBlankDocument, wdNewEmailMessage, wdNewFrameset, or wdNewWebPage. The default constant is wdNewBlankDocument.

            Object Visible = true;//Optional Object. True to open the document in a visible window. If this value is False, Microsoft Word opens the document but sets the Visible property of the document window to False. The default value is True.

            try
            {
                Word.Document wordDoc = thisApplication.Documents.Add(ref Template, ref NewTemplate, ref DocumentType, ref Visible);

                thisDocument = wordDoc;
                wDoc = wordDoc;
                WApp = thisApplication;
                return true;
            }
            catch (Exception ex)
            {
                string err = string.Format("創建Word文檔出錯,錯誤原因:{0}", ex.Message);
                throw new Exception(err, ex);
            }

        }

        private static void killWinWordProcess()
        {

            System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("WINWORD");
            foreach (System.Diagnostics.Process process in processes)
            {
                bool b = process.MainWindowTitle == "";
                if (process.MainWindowTitle == "")
                {
                    process.Kill();
                }
            }
        }

       
        #endregion


        #region 文檔另存爲其他文件名
        /// <summary>   
        /// 文檔另存爲其他文件名   
        /// </summary>   
        /// <param name="fileName">文件名</param>   
        /// <param name="wDoc">Document對象</param> 
        public bool SaveAs(string fileName)
        {
            try
            {
                return SaveAs(fileName, wDoc);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion


        #region 文檔另存爲其他文件名
        /// <summary>   
        /// 文檔另存爲其他文件名   
        /// </summary>   
        /// <param name="fileName">文件名</param>   
        /// <param name="wDoc">Document對象</param> 
        public static bool SaveAs(string fileName, Word.Document wDoc)
        {
            Object FileName = fileName;//文檔的名稱。默認值是當前文件夾名和文件名。如果文檔在以前沒有保存過,則使用默認名稱(例如,Doc1.doc)。如果已經存在具有指定文件名的文檔,則會在不先提示用戶的情況下改寫文檔。   

            Object FileFormat = Word.WdSaveFormat.wdFormatDocument;// 文檔的保存格式。可以是任何 WdSaveFormat 值。要以另一種格式保存文檔,請爲 SaveFormat 屬性指定適當的值。

            Object LockComments = false;// 如果爲 true,則鎖定文檔以進行註釋。默認值爲 false。

            Object Password = System.Type.Missing;// 用來打開文檔的密碼字符串。(請參見下面的備註。)   

            Object AddToRecentFiles = false; // 如果爲 true,則將該文檔添加到“文件”菜單上最近使用的文件列表中。默認值爲 true。   

            Object WritePassword = System.Type.Missing; // 用來保存對文件所做更改的密碼字符串。(請參見下面的備註。)   

            Object ReadOnlyRecommended = false;// 如果爲 true,則讓 Microsoft Office Word 在打開文檔時建議只讀狀態。默認值爲 false

            Object EmbedTrueTypeFonts = false;//如果爲 true,則將 TrueType 字體隨文檔一起保存。如果省略的話,則 EmbedTrueTypeFonts 參數假定 EmbedTrueTypeFonts 屬性的值。

            Object SaveNativePictureFormat = true;// 如果圖形是從另一個平臺(例如,Macintosh)導入的,則 true 表示僅保存導入圖形的 Windows 版本。 

            Object SaveFormsData = false;// 如果爲 true,則將用戶在窗體中輸入的數據另存爲數據記錄。   

            Object SaveAsAOCELetter = false;// 如果文檔附加了郵件程序,則 true 表示會將文檔另存爲 AOCE 信函(郵件程序會進行保存)。   

            Object Encoding = System.Type.Missing;// MsoEncoding。要用於另存爲編碼文本文件的文檔的代碼頁或字符集。默認值是系統代碼頁。   

            Object InsertLineBreaks = true;// 如果文檔另存爲文本文件,則 true 表示在每行文本末尾插入分行符。   

            Object AllowSubstitutions = false;//如果文檔另存爲文本文件,則 true 允許 Word 將某些符號替換爲外觀與之類似的文本。例如,將版權符號顯示爲 (c)。默認值爲 false。

            Object LineEnding = Word.WdLineEndingType.wdCRLF;// Word 在另存爲文本文件的文檔中標記分行符和換段符。可以是任何 WdLineEndingType 值。   

            Object AddBiDiMarks = true;//如果爲 true,則向輸出文件添加控制字符,以便保留原始文檔中文本的雙向佈局。   

            try
            {
                wDoc.SaveAs(ref FileName, ref FileFormat, ref LockComments, ref Password, ref AddToRecentFiles, ref WritePassword, ref ReadOnlyRecommended, ref EmbedTrueTypeFonts, ref SaveNativePictureFormat, ref SaveFormsData, ref SaveAsAOCELetter, ref Encoding, ref InsertLineBreaks, ref AllowSubstitutions, ref LineEnding, ref AddBiDiMarks);
                return true;
            }
            catch (Exception ex)
            {
                string err = string.Format("另存文件出錯,錯誤原因:{0}", ex.Message);
                throw new Exception(err, ex);
            }
        }
        #endregion


        #region 關閉文檔
        /// <summary>   
        /// 關閉文檔   
        /// </summary>   
        public void Close()
        {
            Close(wDoc, wApp);
            wDoc = null;
            wApp = null;
        }
        #endregion


        #region 關閉文檔
        /// <summary>   
        /// 關閉文檔   
        /// </summary>   
        /// <param name="wDoc">Document對象</param>   
        /// <param name="WApp">Application對象</param>  
        public static void Close(Word.Document wDoc, Word.Application WApp)
        {
            Object SaveChanges = Word.WdSaveOptions.wdSaveChanges;// 指定文檔的保存操作。可以是下列 WdSaveOptions 值之一:wdDoNotSaveChanges、wdPromptToSaveChanges 或 wdSaveChanges

            Object OriginalFormat = Word.WdOriginalFormat.wdOriginalDocumentFormat;// 指定文檔的保存格式。可以是下列 WdOriginalFormat 值之一:wdOriginalDocumentFormat、wdPromptUser 或 wdWordDocument。   

            Object RouteDocument = false;// 如果爲 true,則將文檔傳送給下一個收件人。如果沒有爲文檔附加傳送名單,則忽略此參數。   

            try
            {
                if (wDoc != null)
                    wDoc.Close(ref SaveChanges, ref OriginalFormat, ref RouteDocument);

                if (WApp != null)
                    WApp.Quit(ref SaveChanges, ref OriginalFormat, ref RouteDocument);

            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        #endregion


        #region
        ///獲取文檔中所有標籤
        ///
        public void GetDocumentBookmarkData(string FileName,ref string[] bookmarks)
        {

            Word.Document wDoc = null;
            Word.Application wApp = null;
            CreateNewWordDocument(FileName, ref wDoc, ref wApp);
            object oEndOfDoc = "\\endofdoc";
            object missing = System.Reflection.Missing.Value;
            int i = 0;

            System.Collections.IEnumerator enu = wApp.ActiveDocument.Bookmarks.GetEnumerator();

            
            while (enu.MoveNext())
            {
               Word.Bookmark bk = (Word.Bookmark)enu.Current;

               bookmarks[i++] = bk.Name.ToString();
              // str += "{" + bk.Name.ToString() + ":" + bk.Range.Text + "}";
            }

            object o = null;

            wDoc.Close(ref missing, ref missing, ref missing);
            wApp.Quit(ref missing, ref missing, ref missing);

            if (wDoc != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wDoc);
                wDoc = null;
            }

            if (wApp != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wApp);
                wApp = null;
            }

            GC.Collect();

        }
        #endregion


        #region 填充書籤
        /// <summary>   
        /// 填充書籤   
        /// </summary>   
        /// <param name="bookmark">書籤</param>   
        /// <param name="value">值</param> 
        public void Replace(string bookmark, string value)
        {
            try
            {
                object bkObj = bookmark;
                if (wApp.ActiveDocument.Bookmarks.Exists(bookmark) == true)
                {
                    wApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select();
                }
                else return;
                wApp.Selection.TypeText(value);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        public void Replace(string bookmark, DataGridView dgv)
        {
            Word.Table mytable;
            Word.Document mydoc = wDoc;
            Word.Application wordApp = wApp;
            Object myobj= System.Reflection.Missing.Value;        

            try
            {
                object bkObj = bookmark;
                if (wApp.ActiveDocument.Bookmarks.Exists(bookmark) == true)
                {
                    wApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select();
                }
                else return;

                if (dgv.RowCount > 0)
                {
                    Word.Range rng3 = wordApp.Selection.Range;
                    ////將數據生成Word表格文件
                    mytable = mydoc.Tables.Add(rng3, dgv.RowCount, dgv.ColumnCount, ref myobj, ref myobj);
                    mytable.Borders.Enable = 1;

                    int intTableCnt = mydoc.Tables.Count;

                    
                    //設置列寬
                    //mydoc.Tables.Item(intTableCnt).Rows.HeightRule = Word.WdRowHeightRule.wdRowHeightAtLeast;
                    //mydoc.Tables.Item(intTableCnt).Rows.Height = wordApp.CentimetersToPoints(float.Parse("0.8"));
                    //mydoc.Tables.Item(intTableCnt).Range.Font.Size = 10;
                    //mydoc.Tables.Item(intTableCnt).Range.Font.Name = "宋體";
                    //mydoc.Tables.Item(intTableCnt).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    //mydoc.Tables.Item(intTableCnt).Range.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;


                    ////設置表格樣式
                    //mydoc.Tables.Item(intTableCnt).Borders.Item(Word.WdBorderType.wdBorderLeft).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
                    //mydoc.Tables.Item(intTableCnt).Borders.Item(Word.WdBorderType.wdBorderLeft).LineWidth = Word.WdLineWidth.wdLineWidth150pt;
                    //mydoc.Tables.Item(intTableCnt).Borders.Item(Word.WdBorderType.wdBorderLeft).Color = Word.WdColor.wdColorAutomatic;

                    //mydoc.Tables.Item(intTableCnt).Borders.Item(Word.WdBorderType.wdBorderTop).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
                    //mydoc.Tables.Item(intTableCnt).Borders.Item(Word.WdBorderType.wdBorderTop).LineWidth = Word.WdLineWidth.wdLineWidth150pt;
                    //mydoc.Tables.Item(intTableCnt).Borders.Item(Word.WdBorderType.wdBorderTop).Color = Word.WdColor.wdColorAutomatic;

                    //mydoc.Tables.Item(intTableCnt).Borders.Item(Word.WdBorderType.wdBorderBottom).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
                    //mydoc.Tables.Item(intTableCnt).Borders.Item(Word.WdBorderType.wdBorderBottom).LineWidth = Word.WdLineWidth.wdLineWidth150pt;
                    //mydoc.Tables.Item(intTableCnt).Borders.Item(Word.WdBorderType.wdBorderBottom).Color = Word.WdColor.wdColorAutomatic;

                    //mydoc.Tables.Item(intTableCnt).Borders.Item(Word.WdBorderType.wdBorderRight).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
                    //mydoc.Tables.Item(intTableCnt).Borders.Item(Word.WdBorderType.wdBorderRight).LineWidth = Word.WdLineWidth.wdLineWidth150pt;
                    //mydoc.Tables.Item(intTableCnt).Borders.Item(Word.WdBorderType.wdBorderRight).Color = Word.WdColor.wdColorAutomatic;

                    //mydoc.Tables.Item(intTableCnt).Borders.Item(Word.WdBorderType.wdBorderHorizontal).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
                    //mydoc.Tables.Item(intTableCnt).Borders.Item(Word.WdBorderType.wdBorderHorizontal).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
                    //mydoc.Tables.Item(intTableCnt).Borders.Item(Word.WdBorderType.wdBorderHorizontal).Color = Word.WdColor.wdColorAutomatic;

                    //mydoc.Tables.Item(intTableCnt).Borders.Item(Word.WdBorderType.wdBorderVertical).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
                    //mydoc.Tables.Item(intTableCnt).Borders.Item(Word.WdBorderType.wdBorderVertical).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
                    //mydoc.Tables.Item(intTableCnt).Borders.Item(Word.WdBorderType.wdBorderVertical).Color = Word.WdColor.wdColorAutomatic;


                    wordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;//設置右對齊

                    mytable.Columns.SetWidth(100, Word.WdRulerStyle.wdAdjustNone);

                    //輸出列標題數據
                    for (int i = 0; i < dgv.ColumnCount; i++)
                    {
                        mytable.Cell(1, i + 1).Range.Text=dgv.Columns[i].HeaderText;
                    }

                    //輸出控件中的記錄
                    for (int i = 0; i < dgv.RowCount - 1; i++)
                    {
                        for (int j = 0; j < dgv.ColumnCount; j++)
                        {
                            //MessageBox.Show(dgv[j, i].Value.ToString());
                            if (dgv[j, i].Value!=null)
                            mytable.Cell(i + 2, j + 1).Range.Text=dgv[j, i].Value.ToString();
                        }
                        System.Windows.Forms.Application.DoEvents();
                    }

                    mydoc.Paragraphs.Last.Range.Text = "\n";
                }

               // wApp.Selection.ta
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                //throw ex;
            }
            
        }




        //查找表格
        public bool FindTable(string bookmarkTable)
        {
            try
            {
                object bkObj = bookmarkTable;
                if (wApp.ActiveDocument.Bookmarks.Exists(bookmarkTable) == true)
                {
                    wApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select();
                    return true;
                }
                else
                    return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        //移動到下一個單元格
        public void MoveNextCell()
        {
            try
            {
                Object unit = Word.WdUnits.wdCell;
                Object count = 1;
                wApp.Selection.Move(ref unit, ref count);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //填充單元格內容
        public void SetCellValue(string value)
        {
            try
            {
                wApp.Selection.TypeText(value);
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        //移動到下一行
        public void MoveNextRow()
        {
            try
            {
                Object extend = Word.WdMovementType.wdExtend;
                Object unit = Word.WdUnits.wdCell;
                Object count = 1;
                wApp.Selection.MoveRight(ref unit, ref count, ref extend);
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        
    }
}

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