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);
}
}
}
06-02
5722
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)