以编程方式替换Word文档中文本的最快方法

时间:2010-12-18 17:52:28

标签: .net replace ms-word ms-office

任务是使用.NET替换Word文档中的特定关键字。保持原始格式和文档结构的最快,最可靠的方法是什么?

3 个答案:

答案 0 :(得分:3)

如果您安装了单词,那么它非常简单。

从GAC引用Word doc程序集。您可以加载word文档并替换其中的数据。

这是来自我在这里通过输入客户名称来打印word文档的应用程序。 (剪切和粘贴的部分)

    public void ReplaceWordDoc(ref Document doc, object data)
    {
        object missing = Missing.Value;

        List<ReplacerSearch> search = GetSearchList(data);

        foreach (var searchItem in search)
        {
            foreach (Range tmpRange in ((Document)doc).StoryRanges)
            {
                // Set the text to find and replace
                tmpRange.Find.Text = searchItem.Find;
                tmpRange.Find.Replacement.Text = searchItem.Replace;

                // Set the Find.Wrap property to continue (so it doesn't
                // prompt the user or stop when it hits the end of
                // the section)
                tmpRange.Find.Wrap = WdFindWrap.wdFindContinue;

                // Declare an object to pass as a parameter that sets
                // the Replace parameter to the "wdReplaceAll" enum
                object replaceAll = WdReplace.wdReplaceAll;

                // Execute the Find and Replace -- notice that the
                // 11th parameter is the "replaceAll" enum object
                tmpRange.Find.Execute(ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref replaceAll,
                    ref missing, ref missing, ref missing, ref missing);
            }
        }
    }

^这部分进行查找/替换。 ReplacerSearch列表(哇坏名称)只是两个属性,查找,替换。查找是要查找的文本,替换是要替换的文本。

然后下面的代码,基于给定的文件名(路径/名称),它创建一个单词的实例(我认为)并打开文档,进行替换,然后你可以保存或打印或者什么。

    object  fileName        = string.Empty,
            trueValue       = true,
            missing         = Missing.Value,
            falseValue      = false;
    var     app             = new ApplicationClass();
    var doc = new Document();

try
{
    doc = app.Documents.AddOld(ref fileName, ref missing);
    //doc = app.Documents.Add(ref fileName, ref missing, ref missing, ref missing);

    // Loops through the StoryRanges (sections of the Word doc)
    ReplaceWordDoc(ref doc, item);

    //Save or print...
}
catch (Exception ex)
{
    Helpers.Logger.WriteToEventLog(ex.Message, EventLogEntryType.Error);
}
finally
{
    if (doc != null)
    {
        doc.Close(ref falseValue, ref missing, ref missing);
    }
}

if (app != null)
{
    app.Application.Quit(ref falseValue, ref missing, ref missing);
}

希望有所帮助。

答案 1 :(得分:1)

新的Word文件本质上是XML文档。您可以使用python等语言将它们打开为常规文件,然后搜索您要替换的任何术语。一旦找到它们,只需更改它并保存文件即可。

这可能可以通过字符串库来完成,尽管可能有一种更简单的方法,特别是针对XML文档。

编辑:相同的方法应该适用于在.NET中执行它,现在只注意到标记。

答案 2 :(得分:0)

请看一下使用MS Word的Mail Merge功能,它是为此目的而设计的 看看http://support.microsoft.com/kb/301659

相关问题