C#操作Word之TypeText,写文本

之前我们采用Find.Replacement.Text的方式对word模板上的内容进行替换,Replacement是专门为文本替换而生,但是当我们替换的内容超过一定字符数会出现“字符串参量过长。”异常错误。所以本节我们采用TypeText('字符')来代替原来的Find.Replacement.Text,因为TypeText专职用来写文本用的,所以不会因为字符数影响。

我们还是采用之前的例子,对用户的一个登记信息导入到word,有一个人信息介绍的单元格,该信息很容易超过500个字符

姓名张三性别
籍贯浙江学历本科
家庭地址浙江省未名市未名区未名街
电话12345678省份证号123456789012345678
个人信息介绍aaaaaaaaaaaa……

还是先准备类似的word模板

姓名{name}性别{sex}
籍贯{provinve}学历{education}
家庭地址{address}
电话{telephone}省份证号{cardno}
个人信息介绍{info}

下面上代码

 /// <summary>
        /// 用TypeText替换word中的文本
        /// </summary>
        protected void TypeTextToExcel()
        {
            Word.Application app = null;
            Word.Document doc = null;
            //新的word文档路径
            string newFile = DateTime.Now.ToString("yyyyMMddHHmmssss") + ".doc";
            string physicNewFile = Server.MapPath(newFile);
            try
            {  
                object oMissing = System.Reflection.Missing.Value;
                //模板文档
                object fileName = Server.MapPath("template.doc");
                app = new Word.Application();//创建word应用程序
                //打开模板word文档
                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");
                datas.Add("{info}", new String('a',500));//构造大数据字段
             
                foreach (var item in datas)
                {
                    app.Selection.Find.ClearFormatting();
                    app.Selection.Find.Text = item.Key;//需要查找的字符
                    app.Selection.Find.Execute(); //只负责找到匹配字符          
                    app.Selection.TypeText(item.Value);//在找到的字符区域写数据
                }
                //另存word文档
                doc.SaveAs(physicNewFile,
                oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
                oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
            }
            catch(Exception ex)
            {
               
            }
            finally
            {
                if (doc != null)
                {
                    doc.Close();//关闭文档
                }
                if (app != null)
                {
                    app.Quit();//退出应用程序
                }
            }
        }