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;


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