C# 替换Word文字【包含页眉、页脚、文本框、普通文字的替换】
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ToWord
{
class Program
{
static void Main(string[] args)
{
string sourceFile = @"c:\users\administrator\documents\visual studio 2012\Projects\ToWord\ToWord\WordModel.doc";
string destFile = @"c:\users\administrator\documents\visual studio 2012\Projects\ToWord\ToWord\Model\WordModel.doc";
//复制文件
System.IO.File.Copy(sourceFile, destFile, true);
WordOperate wordOperate = new WordOperate();
wordOperate.Open(destFile);
wordOperate.Replace("[项目名标签]","神没什么项目的");
wordOperate.Replace("[项目编号签]", "神没什么项目的");
wordOperate.Save();
}
}
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace ToWord
{
public class WordOperate : IDisposable
{
private Microsoft.Office.Interop.Word._Application _app;
private Microsoft.Office.Interop.Word._Document _doc;
object _nullobj = System.Reflection.Missing.Value;
/// <summary>
/// 关闭Word进程
/// </summary>
public void KillWinword()
{
var p = Process.GetProcessesByName("WINWORD");
if (p.Any()) p[0].Kill();
}
/// <summary>
/// 打开word文档
/// </summary>
/// <param name="filePath"></param>
public void Open(string filePath)
{
_app = new Microsoft.Office.Interop.Word.ApplicationClass();
object file = filePath;
_doc = _app.Documents.Open(
ref file, ref _nullobj, ref _nullobj,
ref _nullobj, ref _nullobj, ref _nullobj,
ref _nullobj, ref _nullobj, ref _nullobj,
ref _nullobj, ref _nullobj, ref _nullobj,
ref _nullobj, ref _nullobj, ref _nullobj, ref _nullobj);
}
/// <summary>
/// 替换word中的文字
/// </summary>
/// <param name="strOld">查找的文字</param>
/// <param name="strNew">替换的文字</param>
public void Replace(string strOld, string strNew)
{
//替换全局Document
_app.Selection.Find.ClearFormatting();
_app.Selection.Find.Replacement.ClearFormatting();
_app.Selection.Find.Text = strOld;
_app.Selection.Find.Replacement.Text = strNew;
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/71398.html