I'm using DocX library to replace text inside word document. I want to somehow find all strings between "[]" inside my template docx file, for example [Name], [LastName], [Date] etc... and replace it with values which I previously load to datagridview which have same column name(Name, LastName, Date). Here is what I have so far:
foreach (DataGridViewRow dataGridViewRow in list)
{
try
{
string template = txtUcitajTemplate.Text;
string text2 = "Aneksi";
if (!System.IO.Directory.Exists(text2))
{
System.IO.Directory.CreateDirectory(text2);
}
string path = string.Format("{0}.docx", dataGridViewRow.Cells["Name"].Value.ToString());
string path2 = System.IO.Path.Combine(text2, path);
using (DocX document = DocX.Load(template))
{
string patternstart = Regex.Escape("[");
string patternend = Regex.Escape("]");
string regexexpr = patternstart + @"(.*?)" + patternend;
// document.ReplaceText(regexexpr, dataGridViewRow.Cells[0].Value.ToString());
// document.ReplaceText(regexexpr, dataGridViewRow.Cells[1].Value.ToString());
var regex = new regex("[.*?]");
var matches = regex.matches(input); //your matches: name, name@gmail.com
foreach (var match in matches) // e.g. you can loop through your matches like this
{
document.ReplaceText(match.ToString(), dataGridViewRow.Cells["Name"].Value.ToString());
document.ReplaceText(match.ToString(), dataGridViewRow.Cells["LastName"].Value.ToString());
}
document.SaveAs(path2);
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}