码迷,mamicode.com
首页 > 其他好文 > 详细

按照word/Excel模板导出word/excel

时间:2015-09-08 09:29:23      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

 

 

最近项目要实现下载打印的功能,想了想,用水晶报表实在是大材小用, 用office组件直接就可以实现这一功能。

引用类 using Microsoft.Office.Interop.Word;

建立两个实体类 一个是导出word需要替换内容的配置,一个是替换内容的实体

public class AgentInfoEntity     {                 private string comname; 

        public string ComName         {             get { return comname; }             set { comname = value; }         }                private string linkname; 

        public string LinkName         {             get { return linkname; }             set { linkname = value; }         }               private string comemail; 

        public string ComEmail         {             get { return comemail; }             set { comemail = value; }         }                 private string sn; 

        public string SN         {             get { return sn; }             set { sn = value; }         } 

            private string comtel; 

        public string ComTel         {             get { return comtel; }             set { comtel = value; }         }                private string comcontact; 

        public string ComContact         {             get { return comcontact; }             set { comcontact = value; }         }        private string registercomname; 

        public string RegisterComName         {             get { return registercomname; }             set { registercomname = value; }         }                 private string regaddresstel; 

        public string RegAddressTel         {             get { return regaddresstel; }             set { regaddresstel = value; }         }                private string bank; 

        public string Bank         {             get { return bank; }             set {bank = value; }         }                 private string tax; 

        public string Tax         {             get { return tax; }             set { tax = value; }         }                private string regtel; 

        public string Regtel         {             get { return regtel; }             set { regtel = value; }         }                 private string sendaddress;         public string SendAddress         {             get { return sendaddress; }             set { sendaddress = value; }         }                 private string postaddress; 

        public string PostAddress         {             get { return postaddress; }             set { postaddress = value; }         } 

                private string agentaccount; 

        public string AgentAccount         {             get { return agentaccount; }             set { agentaccount = value; }         } 

                private string postcontact; 

        public string PostContact         {             get { return postcontact; }             set { postcontact = value; }         } 

            private string invoicetel; 

        public string InvoiceTel         {             get { return invoicetel; }             set { invoicetel = value; }         }                private string financecontact; 

        public string FinanceContact         {             get { return financecontact; }             set { financecontact = value; }         }              private string financetel; 

        public string FinanceTel         {             get { return financetel; }             set { financetel = value; }         }             private string financefax; 

        public string FinanceFax         {             get { return financefax; }             set { financefax = value; }         }                 private string financepost; 

        public string FinancePost         {             get { return financepost; }             set { financepost = value; }         }             private string deliveryarea; 

        public string DeliveryArea         {             get { return deliveryarea; }             set { deliveryarea = value; }         }                private string deliverypost; 

        public string DeliveryPost         {             get { return deliverypost; }             set { deliverypost = value; }         }     }

   public class AgentInfoEntity     {        private string comname; 

        public string ComName         {             get { return comname; }             set { comname = value; }         }          private string linkname; 

        public string LinkName         {             get { return linkname; }             set { linkname = value; }         }               private string comemail; 

        public string ComEmail         {             get { return comemail; }             set { comemail = value; }         }          private string sn; 

        public string SN         {             get { return sn; }             set { sn = value; }         } 

       private string comtel; 

        public string ComTel         {             get { return comtel; }             set { comtel = value; }         }          private string comcontact; 

        public string ComContact         {             get { return comcontact; }             set { comcontact = value; }         }                private string registercomname; 

        public string RegisterComName         {             get { return registercomname; }             set { registercomname = value; }         }               private string regaddresstel; 

        public string RegAddressTel         {             get { return regaddresstel; }             set { regaddresstel = value; }         }       private string bank; 

        public string Bank         {             get { return bank; }             set {bank = value; }         }         private string tax; 

        public string Tax         {             get { return tax; }             set { tax = value; }         }         private string regtel; 

        public string Regtel         {             get { return regtel; }             set { regtel = value; }         }          private string sendaddress;         public string SendAddress         {             get { return sendaddress; }             set { sendaddress = value; }         }             private string postaddress; 

        public string PostAddress         {             get { return postaddress; }             set { postaddress = value; }         } 

             private string agentaccount; 

        public string AgentAccount         {             get { return agentaccount; }             set { agentaccount = value; }         } 

             private string postcontact; 

        public string PostContact         {             get { return postcontact; }             set { postcontact = value; }         } 

              private string invoicetel; 

        public string InvoiceTel         {             get { return invoicetel; }             set { invoicetel = value; }         }                private string financecontact; 

        public string FinanceContact         {             get { return financecontact; }             set { financecontact = value; }         }               private string financetel; 

        public string FinanceTel         {             get { return financetel; }             set { financetel = value; }         }             private string financefax; 

        public string FinanceFax         {             get { return financefax; }             set { financefax = value; }         }              private string financepost; 

        public string FinancePost         {             get { return financepost; }             set { financepost = value; }         }                 private string deliveryarea; 

        public string DeliveryArea         {             get { return deliveryarea; }             set { deliveryarea = value; }         }                private string deliverypost; 

        public string DeliveryPost         {             get { return deliverypost; }             set { deliverypost = value; }         }     }

     /// <summary>       /// l根据实体取得属性的值。       /// </summary>       /// <param name="ainfo"></param>       /// <param name="key"></param>       /// <returns></returns>       public string getProperties(AgentInfoEntity ainfo,string key)       {           string tStr = string.Empty;           if (ainfo== null)           {               return tStr;           }           System.Reflection.PropertyInfo[] properties = ainfo.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); 

          if (properties.Length <= 0)           {               return tStr;           }           foreach (System.Reflection.PropertyInfo item in properties)           {               string name = item.Name;               object value = item.GetValue(ainfo,null);               if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))               {                   //tStr += string.Format("{0}:{1},", name, value);                   if (name.ToLower() == key)                   {                       tStr =(string)value;                       break;                   }               }           }           return tStr;       }

      /// <summary>       /// 替换内容并导出       /// </summary>       /// <param name="templetePathandName"></param>       /// <param name="saasPathandFile"></param>

     /// <param name="eword"></param>

     /// <param name="agentinfo"></param>       /// <returns></returns>

public void ExportWordForTemplete(string templetePathandName,string saasPathandFile,ExWordValue eword,AgentInfoEntity agentinfo)         {             //生成WORD程序对象和WORD文档对象             string p_TemplatePath = templetePathandName; //例如"/templete.doc";             string p_SavePath = saasPathandFile;             Application appWord = new Application();             Document doc = new Document(); 

            object oMissing = System.Reflection.Missing.Value;//这是一个疑问

            //打开模板文档,并指定doc的文档类型             object filename = "";             try             {                 object objTemplate = Server.MapPath(p_TemplatePath);                 object objDocType = WdDocumentType.wdTypeDocument;                 object objFalse = false, objTrue = true;                 doc = (Document)appWord.Documents.Add(ref objTemplate, ref objFalse, ref objDocType, ref objTrue);                 //获取模板中所有的书签                 Bookmarks odf = doc.Bookmarks;                 //循环所有的书签,并给书签赋值                 for (int oIndex = 0; oIndex <eword.ItemValue.Count ; oIndex++)                 {                     object obDD_Name =eword.ItemValue[oIndex];                     doc.Bookmarks.get_Item(ref obDD_Name).Range.Text = getProperties(agentinfo, (string)obDD_Name);                     //p_TestReportTable.Rows[0][testTablevalues[oIndex]].ToString();//此处Range也是WORD中很重要的一个对象,就是当前操作参数所在的区域                 }                 //第四步 生成word,将当前的文档对象另存为指定的路径,然后关闭doc对象。关闭应用程序                 filename = Server.MapPath(saasPathandFile);                 object miss = System.Reflection.Missing.Value;                 doc.SaveAs(ref filename, 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, ref miss);                 object missingValue = Type.Missing;                 object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;                 doc.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);                 appWord.Application.Quit(ref miss, ref miss, ref miss);                 doc = null;                 appWord = null;

            }             catch (System.Threading.ThreadAbortException ex)             {                 object miss = System.Reflection.Missing.Value;                 object missingValue = Type.Missing;                 object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;                 doc.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);                 appWord.Application.Quit(ref miss, ref miss, ref miss);             }

             //导出            string file = filename.ToString();             FileInfo fi = new FileInfo(file);             Response.Clear();             Response.ClearHeaders();             Response.Buffer = false;             //Response.AppendHeader("Content-Disposition","attachment;filename=" +HttpUtility.UrlEncode(Path.GetFileName(destFileName),System.Text.Encoding.Default));             Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(Path.GetFileName(file), System.Text.Encoding.UTF8));             Response.AppendHeader("Content-Length", fi.Length.ToString());             Response.ContentType = "application/octet-stream";             Response.WriteFile(file);             Response.Flush();             Response.End();         }

 

   以上是代码,但是对于引用的dll它是com组件,如果不对它的权限进行设置将会报错。

    调用COM组件发布IIS时常见错误 80070005解决方案

症状:

oWordApplic = New Word.Application

当程序运行到这句时出现下面的错误:

检索 COM 类工厂中 CLSID 为 {000209FF-0000-0000-C000-000000000046} 的组件时失败,原因是出现以下错误: 80070005。

oWordApplic = New Word.Application

当程序运行到这句时出现下面的错误:

检索 COM 类工厂中 CLSID 为 {000209FF-0000-0000-C000-000000000046} 的组件时失败,原因是出现以下错误: 80070005。

解决方法一:

控制面板-》管理工具-》组件服务-》计算机-》我的电脑-》DCom配置-》找到Microsoft Word文档

之后

单击属性打开此应用程序的属性对话框。  

2. 单击标识选项卡,然后选择交互式用户。

3.单击"安全"选项卡,分别在"启动和激活权限"和"访问权限"组中选中"自定义",然后

自定义->编辑->添加ASP.NET账户和IUSER_计算机名

* 这些帐户仅在计算机上安装有 IIS 的情况下才存在。

13. 确保允许每个用户访问,然后单击确定。

14. 单击确定关闭 DCOMCNFG。

解决方法二:

如果上述方法不能解决问题,就应该是权限问题,请尝试用下面的方法:

在web.config中使用身份模拟,在<system.web>节中加入   <identity impersonate="true" userName="你的用户名" password="密码"/>

</system.web>

按照word/Excel模板导出word/excel

标签:

原文地址:http://www.cnblogs.com/hcf-0320/p/4790566.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!