テンプレートとしてWord文書があり、プレースホルダーを置き換えたい。#テキスト行数のアドレス。これは、Environment.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);
}
}