我想遍历文档中的所有书签,并将文本设置为每个bookmark.Name来自datagridview单元格已经加载的值。我在这个循环中被困在这里。请问有什么建议吗?
using (Novacode.DocX document = DocX.Load(template))
{
foreach (Novacode.Bookmark bookmark in document.Bookmarks)
{
//MessageBox.Show("\tFound bookmarks {0}", bookmark.Name);
//var bookmarks = bookmark.Name;
//document.Bookmarks[bookmark.Name].SetText(dataGridViewRow.Cells[0].Value.ToString());
int i = document.Bookmarks.Count;
var bookmarks = document.Bookmarks[i].Name;
document.Bookmarks[bookmark.Name].SetText(dataGridViewRow.Cells[0].Value.ToString());
document.Bookmarks[0].SetText(dataGridViewRow.Cells[1].Value.ToString());
document.Bookmarks[1].SetText(dataGridViewRow.Cells[2].Value.ToString());
document.Bookmarks[2].SetText(dataGridViewRow.Cells[3].Value.ToString());
document.Bookmarks[3].SetText(dataGridViewRow.Cells[4].Value.ToString());
//document.Bookmarks[bookmark.Name].SetText(dataGridViewRow.Cells[2].Value.ToString());
//document.Bookmarks[bookmark.Name].SetText(dataGridViewRow.Cells[3].Value.ToString());
//document.Bookmarks[bookmark.Name].SetText(dataGridViewRow.Cells[4].Value.ToString());
//document.Bookmarks[bookmark.Name].SetText(dataGridViewRow.Cells[5].Value.ToString());
//document.Bookmarks[bookmark.Name].SetText(dataGridViewRow.Cells[6].Value.ToString());
//document.Bookmarks[bookmark.Name].SetText(dataGridViewRow.Cells[7].Value.ToString());
//document.Bookmarks[bookmark.Name].SetText(dataGridViewRow.Cells[8].Value.ToString());
//document.Bookmarks[bookmark.Name].SetText(dataGridViewRow.Cells[9].Value.ToString());
//document.Bookmarks[bookmark.Name].SetText(dataGridViewRow.Cells[10].Value.ToString());
//document.Bookmarks[bookmark.Name].SetText(dataGridViewRow.Cells[11].Value.ToString());
}
document.SaveAs(path2);
}
答案 0 :(得分:0)
如果我理解正确,那么这就是你想要通过循环实现的目标:
using (Novacode.DocX document = DocX.Load(template))
{
int i = 0;
foreach (Novacode.Bookmark bookmark in document.Bookmarks)
{
var bookmarks = document.Bookmarks[i].Name;
document.Bookmarks[bookmark.Name].SetText(dataGridViewRow.Cells[i+1].Value.ToString());
i++;
}
document.SaveAs(path2);
}
我们在这里所做的是声明一个变量i
,它在循环之外但是我们在每次foreach迭代时增加它的值。或者,您可以重写循环并改为使用for
循环:
for(int i=0; i< document.Bookmarks.Count)
{
//change the code here accordingly
}
如果这有帮助,请告诉我。 谢谢。