单词互操作;用换行符替换一些文本

时间:2013-02-12 10:25:53

标签: c# ms-word office-interop

我有一个word文档作为模板,我想替换占位符;带有多行文本的#Address。 它的工作原理除了环境.NewLine被忽略。那么我该如何为每一个新行添加换行符呢? 我应该指出,在代码中,addressLines是一个由逗号和标准新行常量分隔的集合中每一行组成的字符串。

public static void PrintAddress(string companyName, List<string> lines, string outputFolder)
{
    // TODO put in linebreak for each line of the address
    lines.Insert(0, companyName);
    var lineEnd = "," + Environment.NewLine;
    var addressLines = string.Join(lineEnd, lines.ToArray());
    var application = new Application();
    var path = Path.Combine(HttpContext.Current.Server.MapPath(AppSettings.UploadFolder), SessionObjectsSCD.UploadedFile.FileName);
    var document = application.Documents.Open(path);
    WordDocumentClass.FindAndReplace(document, "#ADDRESS", addressLines);
    object filename = string.Format("{0}/{1}.docx", outputFolder, companyName);
    document.SaveAs(ref filename);

    // TODO print document

    application.Quit();
}

public static void FindAndReplace(Document document, string placeHolder, string newText)
{
    object missingObject = null;
    object item = WdGoToItem.wdGoToPage;
    object whichItem = WdGoToDirection.wdGoToFirst;
    object replaceAll = WdReplace.wdReplaceAll;
    object forward = true;
    object matchAllWord = true;
    object matchCase = false;
    object originalText = placeHolder;
    object replaceText = newText;

    document.GoTo(ref item, ref whichItem, ref missingObject, ref missingObject);
    foreach (Range rng in document.StoryRanges)
    {
        rng.Find.Execute(
            ref originalText,
            ref matchCase,
            ref matchAllWord,
            ref missingObject,
            ref missingObject,
            ref missingObject,
            ref forward,
            ref missingObject,
            ref missingObject,
            ref replaceText,
            ref replaceAll,
            ref missingObject,
            ref missingObject,
            ref missingObject,
            ref missingObject);
    }
}

2 个答案:

答案 0 :(得分:2)

我发现这就是答案; var lineEnd =&#34;,\ x0B&#34 ;;

下次我将尝试另一个答案中提到的Open XML Toolkit。

答案 1 :(得分:1)

我建议不要使用Office Interop。 更好的方法是使用Open XML Toolkit,然后像MailMerge一样处理它。 有很多文章,但这是一个开始:

http://blogs.msdn.com/b/ericwhite/archive/2009/02/05/move-insert-delete-paragraphs-in-word-processing-documents-using-the-open-xml-sdk.aspx