简体   繁体   English

C# 从一个word文档中复制一个表格,并添加到另一个word文档中

[英]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.我想从 MS Word 文档中获取一个表格,并将该表格添加到另一个具有所有格式的文档中。 I am using OOXML to do this.我正在使用 OOXML 来执行此操作。 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.为了识别一个特定的表格,我分配了“Alt Text -> Title”,我可以从源文档中获取表格及其内容。 I have added a table to destination document with specific "Alt Text -> Title and able to get it also.我已经在目标文档中添加了一个表格,其中包含特定的“Alt Text -> Title 并且也能够获取它。

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 错误消息。

MS Word Error -> "The file is corrupt and cannot be opened." MS Word 错误 -> “文件已损坏,无法打开。”

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."当我针对此错误单击“确定”时,它显示消息“Word 在 .docx 中发现不可读的内容。您要恢复此文档的内容吗?如果您信任此文档的来源,请单击“是”。 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();

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.这个问题能够将表格从一个 Word 文档复制到另一个文档,并且上述代码可以很好地实现相同的效果。

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.对于超链接问题,我将发布单独的问题并关闭此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM