c#操作word替换文字

using System;
using System.Windows.Forms;
using MSWord = Microsoft.Office.Interop.Word;

namespace word_test
{
    public partial class Form1 : Form
    {
        MSWord.Application app = null;
        MSWord.Document doc = null;

        public Form1()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //将要导出的新word文件名
            string physicNewFile = @"C:\Users\***\Desktop\test.docx";
            app = new MSWord.Application();//创建word应用程序
            object fileName = (physicNewFile);//模板文件

            //打开模板文件
            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);

            object replace = MSWord.WdReplace.wdReplaceAll;

            app.Selection.Find.Replacement.ClearFormatting();
            app.Selection.Find.MatchWholeWord = true;
            app.Selection.Find.ClearFormatting();
            app.Selection.Find.Text = "A*A";//需要被替换的文本
            app.Selection.Find.Replacement.Text = textBox1.Text;//替换文本

            //执行替换操作
            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);
            //对替换好的word模板另存为一个新的word文档
            doc.SaveAs(@"C:\Users\***\Desktop\test_out.docx",
            oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
            oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);

            //关闭wordDoc文档
            app.Documents.Close(ref oMissing, ref oMissing, ref oMissing);
            //关闭wordApp组件对象
            app.Quit(ref oMissing, ref oMissing, ref oMissing);
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值