DocX clone table and insert at index

白昼怎懂夜的黑 提交于 2019-12-03 20:12:26

问题


I am using C# to make a simple Windows app using Novacode to manipulate a Word document.

I have a source table in my Word document that I want to clone. I am able to find the source table okay using this code:

Table sourceTable = document.Tables[3]; 

I can see by the rows and columns that this is in fact the table that I want to clone.

I have a string in my Word doc that right after it I want to insert my cloned source table. In fact, I may need to insert it more than once.

I don't know how to find my string, the index of it, and then insert the one or more cloned tables at that index.

Thanks.


回答1:


Here is how I do it, I use a tag that I insert and replace with table:

// Add a Table to this document.
var table = document.AddTable(2, 3);

// Specify some properties for this Table.
table.Alignment = Alignment.center;

// Add content to this Table.
table.Rows[0].Cells[0].Paragraphs.First().Append("A");
table.Rows[0].Cells[1].Paragraphs.First().Append("B");
table.Rows[0].Cells[2].Paragraphs.First().Append("C");
table.Rows[1].Cells[0].Paragraphs.First().Append("D");
table.Rows[1].Cells[1].Paragraphs.First().Append("E");
table.Rows[1].Cells[2].Paragraphs.First().Append("F");

// Insert table at index where tag #TABLE# is in document.
document.InsertTable(table));
foreach (var paragraph in document.Paragraphs)
{
    paragraph.FindAll("#TABLE#").ForEach(index => paragraph.InsertTableAfterSelf((table)));
}

//Remove tag
document.ReplaceText("#TABLE#", ""); 


来源:https://stackoverflow.com/questions/24534638/docx-clone-table-and-insert-at-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!