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();//退出应用程序
                }
            }
        }

 

转载于:https://www.cnblogs.com/fuyun2000/archive/2013/06/16/3138547.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
VB访问word书签。 '实现代码如下 Dim cn As New ADODB.Connection Dim AdoRs As New ADODB.Recordset Dim WordTemps As New Word.Application Private Sub Form_Load() If cn.State = 1 Then cn.Close End If cn.CursorLocation = adUseClient cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\db1.mdb" End Sub '开始导出数据 Private Sub Command1_Click() Dim strSQl As String Dim REC As Integer Dim i As Integer WordTemps.Documents.Add App.Path + "\货物合同.doc", False WordTemps.Selection.GoTo wdGoToBookmark, , , "合同标题" WordTemps.Selection.TypeText "关于冬季货物的成交合同" WordTemps.Selection.GoTo wdGoToBookmark, , , "合同编号" WordTemps.Selection.TypeText "2004000001" WordTemps.Selection.GoTo wdGoToBookmark, , , "签约单位" WordTemps.Selection.TypeText "宏大科技公司,天天科技公司" WordTemps.Selection.GoTo wdGoToBookmark, , , "签约地址" WordTemps.Selection.TypeText "北京中关村大厦" WordTemps.Selection.GoTo wdGoToBookmark, , , "签约时间" WordTemps.Selection.TypeText fromat(Now, "yyyy-mm-dd") strSQl = "select * from Matrixs" AdoRs.Open strSQl, cn, adOpenKeyset, adLockOptimistic REC = AdoRs.RecordCount If REC < 1 Then MsgBox "无商品记录!", vbOKOnly, "提示" AdoRs.Close Exit Sub Else AdoRs.MoveFirst WordTemps.Selection.GoTo wdGoToBookmark, , , "货物清单" For i = 1 To REC WordTemps.Selection.TypeText AdoRs!名称 WordTemps.Selection.MoveRight unit:=wdCharacter, Count:=1 '右移一格 WordTemps.Selection.TypeText AdoRs!数量 WordTemps.Selection.MoveRight unit:=wdCharacter, Count:=1 '右移一格 WordTemps.Selection.TypeText AdoRs!规格 AdoRs.MoveNext If AdoRs.EOF = False Then WordTemps.Selection.InsertRowsBelow 1 '表格换行 End If Next i AdoRs.Close WordTemps.Visible = True '显示WORD窗口 End If End Sub '实现代码如下 Dim cn As New ADODB.Connection Dim AdoRs As New ADODB.Recordset Dim WordTemps As New Word.Application Private Sub Form_Load() If cn.State = 1 Then cn.Close End If cn.CursorLocation = adUseClient cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\db1.mdb" End Sub '开始导出数据 Private Sub Command1_Click() Dim strSQl As String Dim REC As Integer Dim i As Integer WordTemps.Documents.Add App.Path + "\货物合同.doc", False WordTemps.Selection.GoTo wdGoToBookmark, , , "合同标题" WordTemps.Selection.TypeText "关于冬季货物的成交合同" WordTemps.Selection.GoTo wdGoToBookmark, , , "合同编号" WordTemps.Selection.TypeText "2004000001" WordTemps.Selection.GoTo wdGoToBookmark, , , "签约单位" WordTemps.Selection.TypeText "宏大科技公司,天天科技公司" WordTemps.Selection.GoTo wdGoToBookmark, , , "签约地址" WordTemps.Selection.TypeText "北京中关村大厦" WordTemps.Selection.GoTo wdGoToBookmark, , , "签约时间" WordTemps.Selection.TypeText fromat(Now, "yyyy-mm-dd") strSQl = "select * from Matrixs" AdoRs.Open strSQl, cn, adOpenKeyset, adLockOptimistic REC = AdoRs.RecordCount If REC < 1 Then MsgBox "无商品记录!", vbOKOnly, "提示" AdoRs.Close Exit Sub Else AdoRs.MoveFirst WordTemps.Selection.GoTo wdGoToBookmark, , , "货物清单" For i = 1 To REC WordTemps.Selection.TypeText AdoRs!名称 WordTemps.Selection.MoveRight unit:=wdCharacter, Count:=1 '右移一格 WordTemps.Selection.TypeText AdoRs!数量 WordTemps.Selection.MoveRight unit:=wdCharacter, Count:=1 '右移一格 WordTemps.Selection.TypeText AdoRs!规格 AdoRs.MoveNext If AdoRs.EOF = False Then WordTemps.Selection.InsertRowsBelow 1 '表格换行 End If Next i AdoRs.Close WordTemps.Visible = True '显示WORD窗口 End If End Sub

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值