【发布时间】:2016-07-25 05:33:18
【问题描述】:
我正在使用 DocX 库来替换 word 文档中的文本。我想以某种方式在我的模板 docx 文件中找到“[]”之间的所有字符串,例如 [Name]、[LastName]、[Date] 等......并将其替换为我之前加载到具有相同列的 datagridview 的值姓名(姓名、姓氏、日期)。这是我目前所拥有的:
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);
}
}
【问题讨论】:
-
问题是什么?有什么错误吗?问题?出乎意料的结果?
-
对不起,我不确定我应该在 regex.matches(input) 中输入什么,以搜索孔文档并在 [] 之间找到所有字符串
标签: c# search replace find docx