2013-02-12 48 views
1

我有一個Word文檔作爲模板,我想替換佔位符; #地址包含多行文本。 它的工作原理除了Environment.NewLine被忽略。那麼,我如何爲每條新線路換行呢? 我需要指出的是,在代碼中,addressLines是由集合中的每一行組成的一個字符串,由逗號和標準新行常量分隔。Word interop;用換行符替換一些文本

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

我發現,這就是答案; var lineEnd =「,\ x0B」;

下次我將嘗試Open XML Toolkit,如其他答案中所述。