Spire.Doc is a professional Word .NET library specifically designed for developers to create, read, write, convert and print Word document files. Get free and professional technical support for Spire.Doc for .NET, Java, Android, C++, Python.

Thu Sep 16, 2021 12:54 pm

Dear support team,

I'm struggeling by the attempt to copy a table (completely with all content and formating).
If the table is the last document object in the document then the copy should be appended to the end of the document.
Otherwise the copy should be inserted right after the original table.

The table to copy might be placed in a table cell, hence it might be a nested table.
In this case the copy needs to be inserted in the same table cell below the original table.

How can this be achieved?

Any help is greatly appreciated.

Kind regards,
Marcus

mgattinger
 
Posts: 65
Joined: Fri May 21, 2021 9:03 am

Thu Sep 16, 2021 4:46 pm

I found a solution but I'm not sure if it is a correct one, though it seems to be :)

Code: Select all
// table is of type Table and document of type Document

// Get the following paragraph.
IDocumentObject nextSibling = table.getNextSibling();
while (nextSibling != null && !(nextSibling instanceof Paragraph)) {
    nextSibling = nextSibling.getNextSibling();
}
Paragraph paragraph = ((Paragraph) nextSibling);
if (paragraph == null) {
    paragraph = table.getDocument().createParagraph();
}

// Create a temporary bookmark where to insert the table copy.
String uniqueIdentifier = "(some unique string)";
paragraph.appendBookmarkStart(uniqueIdentifier);
paragraph.appendBookmarkEnd(uniqueIdentifier);

// Move to bookmark, insert table copy at the bookmark position and remove the temporary bookmark.
BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(document);
bookmarksNavigator.moveToBookmark(uniqueIdentifier);
bookmarksNavigator.insertTable(table.deepClone());
document.getBookmarks().remove(bookmarksNavigator.getCurrentBookmark());

mgattinger
 
Posts: 65
Joined: Fri May 21, 2021 9:03 am

Fri Sep 17, 2021 8:50 am

Hello,

Thanks for your inquiry.
Yes, your code can indeed copy the table in the word file. Besides, there is an easier way to achieve your requirements, you can give it a try.
Code: Select all
DocumentObject tableOwner = table.getOwner();
int index=tableOwner.getChildObjects().indexOf(table);
tableOwner.getChildObjects().insert(index+1,table.deepClone());


If you encounter any problems during testing, to help us investigate further, please provide your input file and your desired output. You can upload them here or send to us ([email protected]) via email. Thanks in advance.

Sincerely,
Brian
E-iceblue support team
User avatar

Brian.Li
 
Posts: 1271
Joined: Mon Oct 19, 2020 3:04 am

Return to Spire.Doc

cron