I have the following program that opens a Word document template using the OpenXML library and replaces a couple of phrases with their counterparts from what will be a database (right now its just dummy data). Something about the if-else struture in the nested foreach
loops bothers me. Is there a better way I can accomplish this task? Would regular expressions be a more viable option?
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System;
namespace OpenXmlSearchExample
{
class Program
{
static void Main(string[] args)
{
string templatePath = @"C:\users\example\desktop\template.dotx";
string resultPath = @"C:\users\example\desktop\OpenXmlExample.docx";
using (WordprocessingDocument document = WordprocessingDocument.CreateFromTemplate(templatePath))
{
var body = document.MainDocumentPart.Document.Body;
var paragraphs = body.Elements<Paragraph>();
// Iterate through paragraphs, runs, and text, finding the text we want and replacing it
foreach (Paragraph paragraph in paragraphs)
{
foreach (Run run in paragraph.Elements<Run>())
{
foreach (Text text in run.Elements<Text>())
{
if (text.Text == "Plan")
{
text.Text = string.Format("{0} {1} Plan", DateTime.Now.Year, "Q2");
}
else if (text.Text == "Project Name")
{
text.Text = "SUPER SECRET CODE NAME";
}
else if (text.Text == "WO-nnnn Name")
{
text.Text = "Maintenance";
}
else
{
Console.WriteLine(text.Text);
Console.ReadKey();
}
}
}
}
// Save result document, not modifying the template
document.SaveAs(resultPath);
}
}
}
}