Hi I have a DataTable in C#.
I want to replace the DataTable with the text that says [#mytable] in a .docx file.
I have to replace the DataTable with where it says [#mytable].
Document doc = new Document(true);
doc.LoadFromFile("tableTest.docx");
//Create a simple datatable
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(Int32));
dt.Rows.Add("Andy", 99);
dt.Rows.Add("Nina", 18);
//Find the key word
string key = "[#mytable]";
TextSelection textSelection= doc.FindString(key,false,true);
//Get the TextRange of the key word
TextRange range=textSelection.GetAsOneRange();
//Get it's parent Paragraph
Paragraph parentPara = range.OwnerParagraph;
int rangeIndex = parentPara.ChildObjects.IndexOf(range);
//Create temp bookmark
BookmarkStart start = new BookmarkStart(doc,"testBookmark");
BookmarkEnd end = new BookmarkEnd(doc, "testBookmark");
//Insert the start and end tags of the bookmark on either side of the key word.
parentPara.ChildObjects.Insert(rangeIndex, start);
parentPara.ChildObjects.Insert(rangeIndex+2,end);
//Locate the bookmark.
BookmarksNavigator navigator = new BookmarksNavigator(doc);
navigator.MoveToBookmark("testBookmark");
//Create a object of Spire.Doc.Table
Table table = new Table(doc);
//Reset the rows and columns based on the datatable
table.ResetCells(dt.Rows.Count+1, dt.Columns.Count);
//Fill header row
int i = 0;
foreach(DataColumn dataColumn in dt.Columns){
table[0, i++].AddParagraph().AppendText(dataColumn.ColumnName);
}
//Fill data rows
for (i = 0; i < dt.Rows.Count; i++)
{
DataRow row = dt.Rows[i];
for(int j = 0; j < row.ItemArray.Length; j++)
{
table[i + 1, j].AddParagraph().AppendText(row.ItemArray[j].ToString());
}
}
//Create a body to contains the table
TextBodyPart body = new TextBodyPart(doc);
body.BodyItems.Add(table);
//Replace the whole body between the bookmark tags using the new body
navigator.ReplaceBookmarkContent(body);
//Remove the temp bookmark
doc.Bookmarks.Remove(navigator.CurrentBookmark);
//Save the file to disk
doc.SaveToFile("output.docx",FileFormat.Docx);