Word模板导出

一、步骤:

1.在Word中建立书签;
2.编写C#代码: 

(1) 数据准备

[html]  view plain  copy
  1. /// <summary>  
  2.        /// 数据准备  
  3.        /// </summary>   
  4.        /// <returns></returns>  
  5.        public static string CreateRoCreditCycleWord(RoCreditCycle objRoCreditCycle)  
  6.        {  
  7.            string tempName = "RoPassengerCreditInfo";;  
  8.            string fileName = String.Format("RoPassengerCreditInfo{0}.{1}", new String[] { Guid.NewGuid().ToString("N"), "doc" });  
  9.            string mPath = SysConfig.RoCreditWordPath + DateTime.Now.ToString("yyyyMM") + "/";  
  10.   
  11.            Hashtable htParam = new Hashtable();  
  12.            htParam.Add("lblOwnerLicenseNum", objRoCreditCycle.OwnerLicenseNum);  
  13.            htParam.Add("lblOwnerName1", objRoCreditCycle.OwnerName);   
  14.              
  15.            IList<RoCreditCycleBranch> lstBranch = BaseBLLFactory.CreateService<RoCreditCycleService>().GetRoCreditCycleBranchList(objRoCreditCycle.CycleId);  
  16.                
  17.            Utils.GenerateWord(tempName, fileName, htParam,lstBranch);  
  18.   
  19.            return mPath + fileName;  
  20.        }  
(2)生成Word
[html]  view plain  copy
  1.         /// <summary>  
  2.         /// 生成Word文档  
  3.         /// </summary>  
  4.         /// <param name="temp">模板名称</param>  
  5.         /// <param name="fileName">文件名称</param>  
  6.         /// <param name="param">书签键值对</param>  
  7.         /// <param name="lstBranch">表格数据</param>   
  8.         private static void GenerateWord(string temp, string fileName, Hashtable param, IList<RoCreditCycleBranch> lstBranch)  
  9.         {  
  10.             Microsoft.Office.Interop.Word._Application appWord = new Microsoft.Office.Interop.Word.ApplicationClass();  
  11.             Microsoft.Office.Interop.Word._Document docFile = null;  
  12.             string mPhysicalPath = SysConfig.RoCreditWordPhysicalPath + DateTime.Now.ToString("yyyyMM") + "/";  
  13.             try  
  14.             {  
  15.                 System.IO.Directory.CreateDirectory(mPhysicalPath);  
  16.                 appWord.Visible = false;  
  17.                 object objTrue = true;  
  18.                 object objFalse = false;  
  19.   
  20.                 object objTemplate = SysConfig.CreditTemplatePhysicalPath + String.Format("{0}.dot", temp);  
  21.                 object objDocType = Microsoft.Office.Interop.Word.WdDocumentType.wdTypeDocument;  
  22.                 docFile = appWord.Documents.Add(ref objTemplate, ref objFalse, ref objDocType, ref objTrue);  
  23.   
  24.                 foreach (DictionaryEntry de in param)  
  25.                 {  
  26.                     object mark = de.Key;  
  27.                     if (docFile.Bookmarks.Exists(mark.ToString())  
  28.                         && de.Value != null  
  29.                         && !string.IsNullOrEmpty(de.Value.ToString())) //一般文本示例  
  30.                     {  
  31.                         docFile.Bookmarks.get_Item(ref mark).Range.Text = Convert.ToString(de.Value);  
  32.                     }  
  33.                     else if (mark.ToString() == "lblCurrentLevel") //CheckBox示例  
  34.                     {  
  35.                         string[] strcodes = Convert.ToString(de.Value).Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);  
  36.                         foreach (string strcode in strcodes)  
  37.                         {  
  38.                             switch (strcode)  
  39.                             {  
  40.                                 case "1":  
  41.                                     docFile.Bookmarks.get_Item("cbLevel1").Range.Text = "?";  
  42.                                     break;  
  43.                                 case "2":  
  44.                                     docFile.Bookmarks.get_Item("cbLevel2").Range.Text = "?";  
  45.                                     break;  
  46.                                 case "3":  
  47.                                     docFile.Bookmarks.get_Item("cbLevel3").Range.Text = "?";  
  48.                                     break;  
  49.                                 case "4":  
  50.                                     docFile.Bookmarks.get_Item("cbLevel4").Range.Text = "?";  
  51.                                     break;  
  52.                             }  
  53.                         }  
  54.                     }    
  55.                     else if (mark.ToString() == "lblPhotoPath") //导入图片  
  56.                     {  
  57.                         object oStart = docFile.Bookmarks.get_Item("lblPhoto");  
  58.                         Object linkToFile = false;       //图片是否为外部链接   
  59.                         Object saveWithDocument = true;  //图片是否随文档一起保存    
  60.                         object range = docFile.Bookmarks.get_Item(ref oStart).Range;//图片插入位置       
  61.                         FileInfo filePhotoInfo = new FileInfo(de.Value.ToString());  
  62.                         if (filePhotoInfo.Exists == false)  
  63.                             break;  
  64.                         docFile.InlineShapes.AddPicture(de.Value.ToString(), ref linkToFile, ref saveWithDocument, ref range);  
  65.                         docFile.Application.ActiveDocument.InlineShapes[1].Width = 60;   //设置图片宽度               
  66.                         docFile.Application.ActiveDocument.InlineShapes[1].Height = 70;  //设置图片高度    
  67.                     }  
  68.                 }  
  69.   
  70.                 //表格数据示例  
  71.                 if (docFile.Bookmarks.Exists("tbBranch"))  
  72.                 {  
  73.                     object missing = System.Reflection.Missing.Value;  
  74.   
  75.                     object Bookmark = (int)Microsoft.Office.Interop.Word.WdGoToItem.wdGoToBookmark;  
  76.                     object NameBookMark = "tbBranch";  
  77.                     appWord.Selection.GoTo(ref Bookmark, ref missing, ref missing, ref NameBookMark);  
  78.                     for (int i = 0; i < lstBranch.Count; i++)  
  79.                     {  
  80.                         RoCreditCycleBranch objBranch = lstBranch[i];  
  81.                         appWord.Selection.TypeText(Convert.ToString(i + 1));  
  82.                         missing = System.Reflection.Missing.Value;  
  83.                         object direction = Microsoft.Office.Interop.Word.WdUnits.wdCell;  
  84.                         appWord.Selection.MoveRight(ref direction, ref missing, ref missing);  
  85.                         appWord.Selection.TypeText(objBranch.BranchName);  
  86.                         appWord.Selection.MoveRight(ref direction, ref missing, ref missing);  
  87.                         appWord.Selection.TypeText(objBranch.Address);   
  88.                         //appWord.Selection.MoveRight(ref direction, ref missing, ref missing);  
  89.                         if (i < lstBranch.Count - 1) appWord.Selection.MoveRight(ref direction, ref missing, ref missing);  
  90.                     }  
  91.                 }  
  92.    
  93.                 object fullName = mPhysicalPath + String.Format("{0}", fileName);  
  94.                 object miss = System.Reflection.Missing.Value;  
  95.   
  96.                 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);  
  97.   
  98.                 object missingValue = Type.Missing;  
  99.                 object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;  
  100.                 docFile.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);  
  101.                 appWord.Quit(ref miss, ref miss, ref miss);  
  102.                 docFile = null;  
  103.                 appWord = null;  
  104.             }  
  105.             catch (Exception ex)  
  106.             {  
  107.                 object miss = System.Reflection.Missing.Value;  
  108.                 object missingValue = Type.Missing;  
  109.                 object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;  
  110.                 docFile.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);  
  111.                 appWord.Quit(ref miss, ref miss, ref miss);  
  112.                 docFile = null;  
  113.                 appWord = null;  
  114.                 throw ex;  
  115.             }  
  116.         }  
(3)调用方法,并下载生成的Word

[html]  view plain  copy
  1. /// <summary>  
  2. /// 导出文档  
  3. /// </summary>  
  4. /// <returns></returns>  
  5. protected void ExportRoCreditCycleWord()  
  6. {  
  7.     string file = string.Empty;  
  8.     string FileName = string.Empty;  
  9.   
  10.     string mPhysicalPath = SysConfig.RoCreditWordPhysicalPath + DateTime.Now.ToString("yyyyMM") + "/";  
  11.     string mPath = SysConfig.RoCreditWordPath + DateTime.Now.ToString("yyyyMM") + "/";  
  12.   
  13.     RoCreditCycle objRoCreditCycle = BaseBLLFactory.CreateService<RoCreditCycleService>().GetRoCreditCycle(GetQueryString("CycleId"));  
  14.   
  15.     file = Utils.CreateRoCreditCycleWord(objRoCreditCycle);  
  16.     FileName = file.Substring(file.LastIndexOf("/") + 1);  
  17.   
  18.     FileInfo fileInfo = new FileInfo(mPhysicalPath + FileName);  
  19.     if (fileInfo.Exists == true)  
  20.     {  
  21.         //以字符流的形式下载文件  
  22.         FileStream fs = new FileStream(fileInfo.FullName, FileMode.Open);  
  23.         byte[] bytes = new byte[(int)fs.Length];  
  24.         fs.Read(bytes, 0, bytes.Length);  
  25.         fs.Close();  
  26.   
  27.         Response.ContentType = "application/octet-stream";  
  28.         //通知浏览器下载文件而不是打开  
  29.         Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode(fileInfo.Name, System.Text.Encoding.UTF8));  
  30.         Response.BinaryWrite(bytes);  
  31.         Response.Flush();  
  32.         Response.End();  
  33.     }  
  34. }  

二、注意:

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;


转载自:http://blog.csdn.net/u010678947/article/details/47171799#t1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值