c#操作Word文檔

c#操作Word文檔

using System;

using System.Collections.Generic;
using System.Linq;
using System.Web;
using Word = Microsoft.Office.Interop.Word;
using System.Reflection;
using System.Text.RegularExpressions;
using System.IO;
namespace WebWord
{
    public 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)
            {
                string DocName = System.Configuration.ConfigurationManager.AppSettings["DocName"];
                string DocPath = System.Configuration.ConfigurationManager.AppSettings["DocPath"];
                string AbsolutePath = System.Web.HttpContext.Current.Request.MapPath("~/" + DocPath + "");
                if (!string.IsNullOrEmpty(AbsolutePath))
                    Directory.CreateDirectory(AbsolutePath);
                StreamWriter log2 = new StreamWriter(AbsolutePath + "\\" + "生成Word日誌.txt", true);


                log2.WriteLine("時間:" + System.DateTime.Now.ToLongTimeString() + "生成中……" + ex.Message);


                log2.Close();
                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)
        {
            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);
            }
        }
        #endregion
        #region 文檔另存爲其他文件名
        /// <summary>  
        /// 文檔另存爲其他文件名  
        /// </summary>  
        /// <param name="fileName">文件名</param>  
        /// <param name="wDoc">Document對象</param>  
        public bool OpenWord(string fileName)
        {
            try
            {
                return OpenWord(fileName, wDoc);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
        #region 打開Word文檔
        public static bool OpenWord(string fileName, Word.Document wDoc)
        {
            Object FileName = fileName; // 文檔的名稱。默認值是當前文件夾名和文件名。如果文檔在以前沒有保存過,則使用默認名稱(例如,Doc1.doc)。如果已經存在具有指定文件名的文檔,則會在不先提示用戶的情況下改寫文檔。  
            Word.Application wapp = new Microsoft.Office.Interop.Word.Application();
            wapp.Visible = true;
            object isread = false;
            object isvisible = true;
            object miss = System.Reflection.Missing.Value;


            try
            {
                wapp.Documents.Open(ref FileName, ref miss, ref isread, ref miss, ref miss, ref miss, ref miss, ref miss,
                                  ref miss, ref miss, ref miss, ref isvisible, ref miss, ref miss, ref miss, ref miss);
                return true;
            }
            catch (Exception ex)
            {
                string err = string.Format("另存文件出錯,錯誤原因:{0}", ex.Message);
                throw new Exception(err, ex);
            }
        }
        #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)
        {


            try
            {
                Object SaveChanges = Word.WdSaveOptions.wdSaveChanges;// 指定文檔的保存操作。可以是下列 WdSaveOptions 值之一:wdDoNotSaveChanges、wdPromptToSaveChanges 或 wdSaveChanges。  
                Object OriginalFormat = Word.WdOriginalFormat.wdOriginalDocumentFormat;// 指定文檔的保存格式。可以是下列 WdOriginalFormat 值之一:wdOriginalDocumentFormat、wdPromptUser 或 wdWordDocument。  
                Object RouteDocument = false;// 如果爲 true,則將文檔傳送給下一個收件人。如果沒有爲文檔附加傳送名單,則忽略此參數。  
                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 InsertPicture(string bookmark, string picture)
        {
            try
            {
                object bkObj = bookmark;
                if (wApp.ActiveDocument.Bookmarks.Exists(bookmark) == true)
                {
                    wApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select();
                }
                else return;
                wApp.Selection.InlineShapes.AddPicture(picture);
            }
            catch (Exception ex)
            {
                throw ex;
            }


        }
        #endregion


        #region 添加書籤並插入圖片
        public void AddBookmarkInsertPicture(string bookmark, string picture)
        {
            try
            {
                object miss = System.Reflection.Missing.Value;
                object bkObj = bookmark;
                if (wApp.ActiveDocument.Bookmarks.Exists(bookmark) == true)
                {
                    wApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select();
                    wApp.Selection.InlineShapes.AddPicture(picture);
                }
                else
                {
                    wApp.ActiveDocument.Bookmarks.Add(bookmark, ref miss);
                    wApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select();
                    wApp.Selection.InlineShapes.AddPicture(picture);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }


        }
        #endregion


        #region 添加書籤並填充書籤
        /// <summary>
        /// 
        /// </summary>
        /// <param name="bookmark"></param>
        public void AddBookmarks(string bookmark, string value)
        {
            try
            {
                object miss = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word.Range r = wApp.Selection.Range;
                object bkObj = bookmark;
                if (wApp.ActiveDocument.Bookmarks.Exists(bookmark) == true)
                {
                    wApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select();
                    wApp.Selection.TypeText(value);
                }
                else
                {
                    wApp.ActiveDocument.Bookmarks.Add(bookmark, ref miss);
                    wApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select();
                    wApp.Selection.TypeText(value);
                }


            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #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
        #region 找到表格
        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;
            }
        }
        #endregion


        #region 移動到下一單元格
        public void MoveNextCell()
        {
            try
            {
                Object unit = Word.WdUnits.wdCell;
                Object count = 1;
                wApp.Selection.Move(ref unit, ref count);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
        #region 單元格賦值
        public void SetCellValue(string value)
        {
            try
            {
                wApp.Selection.TypeText(value);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
        #region 移動到下一單行
        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;
            }
        }
        #endregion
        #region 插入文字
        /// <summary>
        /// 插入文字
        /// </summary>
        /// <param name="pText">文本信息</param>
        /// <param name="pFontSize">字體大小</param>
        /// <param name="pFontColor">字體顏色</param>
        /// <param name="pFontBold">字體粗體</param>
        /// <param name="ptextAlignment">字體方向</param>
        public void InsertText(string pText, int pFontSize, Microsoft.Office.Interop.Word.WdColor pFontColor, int pFontBold, Microsoft.Office.Interop.Word.WdParagraphAlignment ptextAlignment)
        {
            //設置字體樣式以及方向   


            wApp.Application.Selection.Font.Name = "宋體";
            wApp.Selection.ParagraphFormat.LineSpacing = 15f;//設置1.5倍行間距
            wApp.Application.Selection.Font.Size = pFontSize;
            wApp.Application.Selection.Font.Bold = pFontBold;
            wApp.Application.Selection.Font.Color = pFontColor;
            wApp.Application.Selection.ParagraphFormat.Alignment = ptextAlignment;
            wApp.Application.Selection.TypeText(pText);
        }
        #endregion
        #region 插入下劃線
        public void InsertUnderLine(string pText)
        {
            wApp.Application.Selection.TypeText(pText);
            wApp.Application.Selection.Font.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineSingle; //設置下劃線
        }
        #endregion
        //插入下劃線
        public void InsertUnderLine(string pText, int pFontSize, Microsoft.Office.Interop.Word.WdColor pFontColor, int pFontBold, Microsoft.Office.Interop.Word.WdParagraphAlignment ptextAlignment)
        {
            wApp.Application.Selection.TypeText(pText);
            wApp.Application.Selection.Font.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineSingle; //設置下劃線
        }


        /// <summary>
        /// 翻頁
        /// </summary>
        public void ToNextPage()
        {
            object breakPage = Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak;
            wApp.Selection.InsertBreak(ref breakPage);
        }


        /// <summary>
        /// 插入段落
        /// </summary>
        public void ToNextParagraph()
        {
            wApp.Selection.TypeParagraph();//插入段落
        }


        /// <summary>
        /// 回車換行
        /// </summary>
        public void ToNextLine()
        {
            wApp.Selection.TypeParagraph();
        }


        #region 是文件名有效
        public string MakeFilenameValid(string filename)
        {
            if (filename == null)
                throw new ArgumentNullException();


            if (filename.EndsWith("."))
                filename = Regex.Replace(filename, @"\.+$", "");


            if (filename.Length == 0)
                throw new ArgumentException();


            if (filename.Length > 245)
                throw new PathTooLongException();


            foreach (char c in System.IO.Path.GetInvalidFileNameChars())
            {
                filename = filename.Replace(c, '_');
            }


            return filename;
        }
        #endregion


        #region 生成Log文件
        /// <summary>
        /// 日誌文件記錄
        /// </summary>
        /// <param name="msg">寫入信息</param>
        public void WriteMsg(string msg)
        {
            try
            {
                //  string path = Path.Combine("./log");
                string path = System.Web.HttpContext.Current.Request.MapPath("~/" + "log");
                if (!Directory.Exists(path))//判斷是否有該文件
                    Directory.CreateDirectory(path);
                string logFileName = path + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";//生成日誌文件
                if (!File.Exists(logFileName))//判斷日誌文件是否爲當天
                    File.Create(logFileName);//創建文件
                StreamWriter writer = File.AppendText(logFileName);//文件中添加文件流
                writer.WriteLine(DateTime.Now.ToString("HH:mm:ss") + " " + msg);
                writer.Flush();
                writer.Close();
            }
            catch (Exception e)
            {
                //   string path =Path.Combine("./log");
                string path = System.Web.HttpContext.Current.Request.MapPath("~/" + "log");
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
                string logFileName = path + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
                if (!File.Exists(logFileName))
                    File.Create(logFileName);
                StreamWriter writer = File.AppendText(logFileName);
                writer.WriteLine(DateTime.Now.ToString("日誌記錄錯誤HH:mm:ss") + " " + e.Message + " " + msg);
                writer.Flush();
                writer.Close();
            }
        }
        #endregion
        public void WriteLog(String msg)
        {
            StreamWriter writer = null;
            try
            {
                string path = System.Web.HttpContext.Current.Request.MapPath("~/" + "log");
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
                writer = File.AppendText(@"a.log");
                writer.WriteLine("{0} {1}", DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss"), msg);
                writer.Flush();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }




        }


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