Search code examples
c#ms-wordopenxml-sdkclonenodeopenxml-table

C# copy a table from a word document and add it to another word document


I want to get a table from a MS Word document and add that table to another document with all it's formatting. I am using OOXML to do this. To identify a specific table I have assigned "Alt Text -> Title" and I am able to get table and it's content from source document. I have added a table to destination document with specific "Alt Text -> Title and able to get it also.

I have used below code to add table to destination document. However when I open destination document it is displaying MS Word error message.

MS Word Error -> "The file is corrupt and cannot be opened."

When I click Ok for this error it is displaying message "Word found unreadable content in .docx. Do you want to recover the contents of this document? If you trust the source of this document, click Yes." when I click Yes.

It displays the destination document with the table and all it's formatting.

How can I remove this error/warning message? What I am doing wrong with code which is causing this error?

NOTE: The table I am trying copy having some text with Hyperlink and that is causing issue. If I remove hyperlink it works fine.

TableProperties tableProperty = sourceDocument.Document.Body.Descendants<TableProperties>().Where(tp => tp.TableCaption != null && tp.TableCaption.Val.InnerText.Contains("sourceTable")).FirstOrDefault();

TableProperties destTableProperty = destinationDocument.Document.Body.Descendants<TableProperties>().Where(tp => tp.TableCaption != null && tp.TableCaption.Val.InnerText.Contains("destinationTable")).FirstOrDefault();

sourceTable = (Table)tableProperty.Parent;
destinationTable = (Table)destTableProperty.Parent;
destinationTable.InsertBeforeSelf<Table>((Table)sourceTable.CloneNode(true));
destinationTable.Remove();


Solution

  • This question was able how to copy a table from one Word document to another and the aforementioned code works fine to achieve the same.

    The cause of warning/error message about document getting corrupt was due to a hyperlink within text of table. If I remove hyperlink it works fine.

    For hyperlink issue I will post separate question and closing this one.