C#操作word之文本替换


C#操作word之文本替换
 姓名 张三 性别 男
 籍贯 浙江 学历 本科
 家庭地址 浙江省未名市未名区未名街
 电话 12345678 省份证号 123456789012345678

假设我们需要将客户的信息导成word文档,其格式类似上面这样的。 我们可以先准备一个word模板,格式如下

 姓名 {name} 性别 {sex}
 籍贯 {provinve} 学历 {education}
 家庭地址 {address}
 电话 {telephone} 省份证号 {cardno}

这里要替换的内容,我们可以定义成数据库中对应的字段,这里为了看上去清晰将要替换的内容用{字段}来代替,你也可以用其他你想要

的方式来定义。

接下来看实现的方式(记得首先在引用中添加相应的组件)

public partial class WebForm3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ReplaceToExcel();
        }
        /// <summary>
        /// 替换word中的文本,并导出word
        /// </summary>
        protected void ReplaceToExcel()
        {
          
            Word.Application app = null;
            Word.Document doc = null;
            //将要导出的新word文件名
            string newFile = DateTime.Now.ToString("yyyyMMddHHmmssss") + ".doc";
            string physicNewFile = Server.MapPath(DateTime.Now.ToString("yyyyMMddHHmmssss") + ".doc");
            try
            {
                app = new Word.Application();//创建word应用程序
                object fileName = Server.MapPath("template.doc");//模板文件
                //打开模板文件
                object oMissing = System.Reflection.Missing.Value;
                doc = app.Documents.Open(ref fileName,
                ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                //构造数据
                Dictionary<string, string> datas = new Dictionary<string, string>();
                datas.Add("{name}", "张三");
                datas.Add("{sex}", "男");
                datas.Add("{provinve}", "浙江");
                datas.Add("{address}", "浙江省杭州市");
                datas.Add("{education}", "本科");
                datas.Add("{telephone}", "12345678");
                datas.Add("{cardno}", "123456789012345678");

                object replace = Word.WdReplace.wdReplaceAll;


              foreach (var item in datas)
                {
                    app.Selection.Find.Replacement.ClearFormatting();
                    app.Selection.Find.ClearFormatting();
                    app.Selection.Find.Text = item.Key;//需要被替换的文本
                    app.Selection.Find.Replacement.Text = item.value;//替换文本

                    //执行替换操作,说明:::下面方法对内容比较少的可以,内容比较多的则会发生内容过长的异常就要使用下面的foreach
                    app.Selection.Find.Execute(
                    ref oMissing, ref oMissing,
                    ref oMissing, ref oMissing,
                    ref oMissing, ref oMissing,
                    ref oMissing, ref oMissing, ref oMissing,
                    ref oMissing, ref replace,
                    ref oMissing, ref oMissing,
                    ref oMissing, ref oMissing);
                }

               /*AppointAprovalSubmitModel document

               foreach (var prop in document.GetType().GetProperties())
                {                    
                        app.Options.ReplaceSelection = true;
                        app.Selection.Find.ClearFormatting();
                        app.Selection.Find.Text = "{" + prop.Name + "}";
                        app.Selection.Find.Replacement.Text = "";
                        app.Selection.Find.Forward = true;
                        //app.Selection.Find.Wrap = 1;
                        app.Selection.Find.Format = false;
                        app.Selection.Find.MatchCase = false;
                        app.Selection.Find.MatchWholeWord = false;
                        app.Selection.Find.MatchByte = true;
                        app.Selection.Find.MatchWildcards = false;
                        app.Selection.Find.MatchSoundsLike = false;
                        app.Selection.Find.MatchAllWordForms = false;
                        app.Selection.Find.Execute(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                        string value = prop.GetValue(document, null).ToString();
                        if (value == null || value == "")
                            value = " ";
                        app.Selection.TypeText(value);
                    }

                */


                //对替换好的word模板另存为一个新的word文档
                doc.SaveAs(physicNewFile,
                oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
                oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);

                //准备导出word
                Response.Clear();
                Response.Buffer = true;
                Response.Charset = "utf-8";
                Response.AddHeader("Content-Disposition", "attachment;filename=" + DateTime.Now.ToString("yyyyMMddHHmmssss") + ".doc");
                Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
                Response.ContentType = "application/ms-word";
                Response.End();
            }
            catch (System.Threading.ThreadAbortException ex)
            {
                //这边为了捕获Response.End引起的异常
            }
            catch (Exception ex)
            {

            }
            finally
            {
                if (doc != null)
                {
                    doc.Close();//关闭word文档
                }
                if (app != null)
                {
                    app.Quit();//退出word应用程序
                }
                //如果文件存在则输出到客户端
                if (File.Exists(physicNewFile))
                {
                    Response.WriteFile(physicNewFile);
                }
            }           
        }
    }

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值