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);
}
}
}
c#操作word替换文字
最新推荐文章于 2025-08-15 15:59:04 发布
该代码示例展示了如何在C#中通过MicrosoftOfficeInterop库打开Word模板文件,查找并替换特定文本,然后保存为新文件。用户输入的文本会替换找到的‘A*A’模式,并保存为test_out.docx。

583

被折叠的 条评论
为什么被折叠?



