C#導出Word總結

一、步驟:

1.在Word中建立書籤;
2.編寫C#代碼: 

(1) 數據準備

	/// <summary>
        /// 數據準備
        /// </summary> 
        /// <returns></returns>
        public static string CreateRoCreditCycleWord(RoCreditCycle objRoCreditCycle)
        {
            string tempName = "RoPassengerCreditInfo";;
            string fileName = String.Format("RoPassengerCreditInfo{0}.{1}", new String[] { Guid.NewGuid().ToString("N"), "doc" });
            string mPath = SysConfig.RoCreditWordPath + DateTime.Now.ToString("yyyyMM") + "/";

            Hashtable htParam = new Hashtable();
            htParam.Add("lblOwnerLicenseNum", objRoCreditCycle.OwnerLicenseNum);
            htParam.Add("lblOwnerName1", objRoCreditCycle.OwnerName); 
            
            IList<RoCreditCycleBranch> lstBranch = BaseBLLFactory.CreateService<RoCreditCycleService>().GetRoCreditCycleBranchList(objRoCreditCycle.CycleId);
              
            Utils.GenerateWord(tempName, fileName, htParam,lstBranch);

            return mPath + fileName;
        }
(2)生成Word
        /// <summary>
        /// 生成Word文檔
        /// </summary>
        /// <param name="temp">模板名稱</param>
        /// <param name="fileName">文件名稱</param>
        /// <param name="param">書籤鍵值對</param>
        /// <param name="lstBranch">表格數據</param> 
        private static void GenerateWord(string temp, string fileName, Hashtable param, IList<RoCreditCycleBranch> lstBranch)
        {
            Microsoft.Office.Interop.Word._Application appWord = new Microsoft.Office.Interop.Word.ApplicationClass();
            Microsoft.Office.Interop.Word._Document docFile = null;
            string mPhysicalPath = SysConfig.RoCreditWordPhysicalPath + DateTime.Now.ToString("yyyyMM") + "/";
            try
            {
                System.IO.Directory.CreateDirectory(mPhysicalPath);
                appWord.Visible = false;
                object objTrue = true;
                object objFalse = false;

                object objTemplate = SysConfig.CreditTemplatePhysicalPath + String.Format("{0}.dot", temp);
                object objDocType = Microsoft.Office.Interop.Word.WdDocumentType.wdTypeDocument;
                docFile = appWord.Documents.Add(ref objTemplate, ref objFalse, ref objDocType, ref objTrue);

                foreach (DictionaryEntry de in param)
                {
                    object mark = de.Key;
                    if (docFile.Bookmarks.Exists(mark.ToString())
                        && de.Value != null
                        && !string.IsNullOrEmpty(de.Value.ToString())) //一般文本示例
                    {
                        docFile.Bookmarks.get_Item(ref mark).Range.Text = Convert.ToString(de.Value);
                    }
                    else if (mark.ToString() == "lblCurrentLevel") //CheckBox示例
                    {
                        string[] strcodes = Convert.ToString(de.Value).Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (string strcode in strcodes)
                        {
                            switch (strcode)
                            {
                                case "1":
                                    docFile.Bookmarks.get_Item("cbLevel1").Range.Text = "?";
                                    break;
                                case "2":
                                    docFile.Bookmarks.get_Item("cbLevel2").Range.Text = "?";
                                    break;
                                case "3":
                                    docFile.Bookmarks.get_Item("cbLevel3").Range.Text = "?";
                                    break;
                                case "4":
                                    docFile.Bookmarks.get_Item("cbLevel4").Range.Text = "?";
                                    break;
                            }
                        }
                    }  
                    else if (mark.ToString() == "lblPhotoPath") //導入圖片
                    {
                        object oStart = docFile.Bookmarks.get_Item("lblPhoto");
                        Object linkToFile = false;       //圖片是否爲外部鏈接 
                        Object saveWithDocument = true;  //圖片是否隨文檔一起保存  
                        object range = docFile.Bookmarks.get_Item(ref oStart).Range;//圖片插入位置     
                        FileInfo filePhotoInfo = new FileInfo(de.Value.ToString());
                        if (filePhotoInfo.Exists == false)
                            break;
                        docFile.InlineShapes.AddPicture(de.Value.ToString(), ref linkToFile, ref saveWithDocument, ref range);
                        docFile.Application.ActiveDocument.InlineShapes[1].Width = 60;   //設置圖片寬度             
                        docFile.Application.ActiveDocument.InlineShapes[1].Height = 70;  //設置圖片高度  
                    }
                }

                //表格數據示例
                if (docFile.Bookmarks.Exists("tbBranch"))
                {
                    object missing = System.Reflection.Missing.Value;

                    object Bookmark = (int)Microsoft.Office.Interop.Word.WdGoToItem.wdGoToBookmark;
                    object NameBookMark = "tbBranch";
                    appWord.Selection.GoTo(ref Bookmark, ref missing, ref missing, ref NameBookMark);
                    for (int i = 0; i < lstBranch.Count; i++)
                    {
                        RoCreditCycleBranch objBranch = lstBranch[i];
                        appWord.Selection.TypeText(Convert.ToString(i + 1));
                        missing = System.Reflection.Missing.Value;
                        object direction = Microsoft.Office.Interop.Word.WdUnits.wdCell;
                        appWord.Selection.MoveRight(ref direction, ref missing, ref missing);
                        appWord.Selection.TypeText(objBranch.BranchName);
                        appWord.Selection.MoveRight(ref direction, ref missing, ref missing);
                        appWord.Selection.TypeText(objBranch.Address); 
                        //appWord.Selection.MoveRight(ref direction, ref missing, ref missing);
                        if (i < lstBranch.Count - 1) appWord.Selection.MoveRight(ref direction, ref missing, ref missing);
                    }
                }
 
                object fullName = mPhysicalPath + String.Format("{0}", fileName);
                object miss = System.Reflection.Missing.Value;

                docFile.SaveAs(ref fullName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument97, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);

                object missingValue = Type.Missing;
                object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
                docFile.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);
                appWord.Quit(ref miss, ref miss, ref miss);
                docFile = null;
                appWord = null;
            }
            catch (Exception ex)
            {
                object miss = System.Reflection.Missing.Value;
                object missingValue = Type.Missing;
                object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
                docFile.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);
                appWord.Quit(ref miss, ref miss, ref miss);
                docFile = null;
                appWord = null;
                throw ex;
            }
        }
(3)調用方法,並下載生成的Word

        /// <summary>
        /// 導出文檔
        /// </summary>
        /// <returns></returns>
        protected void ExportRoCreditCycleWord()
        {
            string file = string.Empty;
            string FileName = string.Empty;

            string mPhysicalPath = SysConfig.RoCreditWordPhysicalPath + DateTime.Now.ToString("yyyyMM") + "/";
            string mPath = SysConfig.RoCreditWordPath + DateTime.Now.ToString("yyyyMM") + "/";

            RoCreditCycle objRoCreditCycle = BaseBLLFactory.CreateService<RoCreditCycleService>().GetRoCreditCycle(GetQueryString("CycleId"));

            file = Utils.CreateRoCreditCycleWord(objRoCreditCycle);
            FileName = file.Substring(file.LastIndexOf("/") + 1);

            FileInfo fileInfo = new FileInfo(mPhysicalPath + FileName);
            if (fileInfo.Exists == true)
            {
                //以字符流的形式下載文件
                FileStream fs = new FileStream(fileInfo.FullName, FileMode.Open);
                byte[] bytes = new byte[(int)fs.Length];
                fs.Read(bytes, 0, bytes.Length);
                fs.Close();

                Response.ContentType = "application/octet-stream";
                //通知瀏覽器下載文件而不是打開
                Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode(fileInfo.Name, System.Text.Encoding.UTF8));
                Response.BinaryWrite(bytes);
                Response.Flush();
                Response.End();
            }
        }

二、注意:

1.Word加完標籤必須另存爲:Word 97-2003模板(*.dot);
2.打開dot文檔時不能雙擊,要右擊“打開”;
3.顯示標籤:選項-高級-勾選【顯示書籤】;
4.表格建立標籤:只需要在第一行第一列建立一個標籤;
5.表格設置: 
(1)表格屬性-列-最小值(不能是固定值);
(2)表格屬性-單元格-選項-勾選【自動換行】;
(3)表格屬性-表格-選項-不勾選【自動重調尺寸以適應內容】。
6.word組件設置:參見:http://blog.csdn.net/zzlrpg/article/details/7109752
(1)在服務器上安裝office.
(2)在"開始"->"運行"中輸入dcomcnfg.exe啓動"組件服務"
(3)依次雙擊"組件服務"->"計算機"->"我的電腦"->"DCOM配置"
(4)在"DCOM配置"中找到"Microsoft word 應用程序",在它上面點擊右鍵,然後點擊"屬性",彈出"Microsoft word 應用程序屬性"對話框
(5)點擊"標識"標籤,選擇"啓動用戶"
(6)點擊"安全"標籤,在"啓動和激活權限"上點擊"自定義",然後點擊對應的"編輯"按鈕,在彈出的"安全性"對話框中填加一個"NETWORK SERVICE"用戶(注意要選擇本計算機名),並給它賦予"本地啓動"和"本地激活"權限.(如果還不行,就加IUser用戶)
(7)依然是"安全"標籤,在"訪問權限"上點擊"自定義",然後點擊"編輯",在彈出的"安全性"對話框中也填加一個"NETWORK SERVICE"用戶,然後賦予"本地訪問"權限.

(8)引入Word的 Interop.word.dll文件

(9)web.config中加入用戶權限配置:

<identity impersonate="true" password="sjstmbs123!@#!@#" userName="administrator" />

7.在DCOM 中不存在WORD、EXCEL等OFFICE組件的解決方法:

MMC進入到我的視線裏面。通過這個終於解決此問題了。先簡單說下,操作步驟(項目演示完成後,補上圖):
(1)Run
(2)MMC -32


(3)File(文件)
(4)Add Remove Snap-in(添加/刪除管理單元)


(5)Component Services(組件服務)
(6)Add(添加)
(7)OK(確定)


(8)Console Root(控制檯根節點)
(9)Component Services(組件服務)
(10)Computers(計算機)
(11)My Computer(我的電腦)
(12)DCOM Config(DCOM配置)
(13)Microsoft Word Application
(14)…


8.參看網址:
(1)http://wenku.baidu.com/view/3963372c7375a417866f8f52.html
(2)http://www.cnblogs.com/eye-like/p/4121219.html

(3)http://blog.sina.com.cn/s/blog_74fe278f0101g75c.html

(4)http://www.cnblogs.com/BoyceLin/archive/2013/03/06/2945655.html(在DCOM 中不存在WORD、EXCEL等OFFICE組件的解決方法)

三、常見錯誤

1.Word“消息篩選器顯示應用程序正在使用中”

答:(1)解決方法僅需將Word的拼寫檢查取消,“文件”–>”選項”–>”校對”,將下圖紅框內的勾選取消即可。


(2)也可在操作Word時添加如下代碼,將拼寫檢查和顯示拼寫錯誤禁用。
Word.Document oDoc = new Word.Document();
oDoc.SpellingChecked=false;
oDoc.ShowSpellingErrors=false;


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