从一个 Word 文档粘贴到另一个文档时丢失格式
Losing Formating when Pasting from one Word Document to another
我有一个程序,它为每个勾选的框打开一个特定的 word 文档,复制文本并将其粘贴到新文档的末尾。
问题是粘贴的文本缺少格式。
因为复制的文本保留在剪贴板上,所以我可以看出它在复制时具有格式,但在粘贴时却没有。
下面是复制粘贴的代码:
foreach (ListViewItem item in checkedItems)
{
//open documents here
path = item.SubItems[1].Text;
objWord.Documents.Open(path);
//copy document text here
objWord.ActiveWindow.Selection.WholeStory();
objWord.ActiveWindow.Selection.Copy();
//close document here
objWord.ActiveDocument.Close();
//paste to end of new document here
newDoc.Activate();
copiedText = Clipboard.GetText();
newDoc.Content.InsertAfter(copiedText);
}
我尝试更改:
copiedText = Clipboard.GetText();
到
copiedText = Clipboard.GetText(TextDataFormat.Rtf);
和
copiedText = Clipboard.GetText(TextDataFormat.Rtf).toString();
两者都没有达到预期的效果。
我进入了文字选项并确保所有粘贴选项都设置为保持源格式。
问题是您声明的任何变量 - 在本例中为 copiedText - 不能 "carry" Word 的格式化命令。您可以使用 "plain text" 的唯一方法是,如果它是有效的 WordOpenXML,那么您需要使用 InsertXML 方法将其放入文档中。对于任何其他带有格式的 Word 都需要一个转换器。当您使用 Paste 方法、Open 方法打开文件或使用 InsertFile 方法将文件插入文档对象时,Word 会自动触发转换器。
通常,我会使用 FormattedText 属性 将格式化的内容从一个文档传送到另一个文档。但在某些特殊情况下,它不包含所需的内容(例如页眉、页脚、页边距)。那么你确实需要 Copy/Paste.
我觉得Word的粘贴方法应该可以。尝试类似的东西:
newDoc.Content.Paste
或者,因为您使用了激活:
Selection.Paste
我有一个程序,它为每个勾选的框打开一个特定的 word 文档,复制文本并将其粘贴到新文档的末尾。
问题是粘贴的文本缺少格式。
因为复制的文本保留在剪贴板上,所以我可以看出它在复制时具有格式,但在粘贴时却没有。
下面是复制粘贴的代码:
foreach (ListViewItem item in checkedItems)
{
//open documents here
path = item.SubItems[1].Text;
objWord.Documents.Open(path);
//copy document text here
objWord.ActiveWindow.Selection.WholeStory();
objWord.ActiveWindow.Selection.Copy();
//close document here
objWord.ActiveDocument.Close();
//paste to end of new document here
newDoc.Activate();
copiedText = Clipboard.GetText();
newDoc.Content.InsertAfter(copiedText);
}
我尝试更改:
copiedText = Clipboard.GetText();
到
copiedText = Clipboard.GetText(TextDataFormat.Rtf);
和
copiedText = Clipboard.GetText(TextDataFormat.Rtf).toString();
两者都没有达到预期的效果。 我进入了文字选项并确保所有粘贴选项都设置为保持源格式。
问题是您声明的任何变量 - 在本例中为 copiedText - 不能 "carry" Word 的格式化命令。您可以使用 "plain text" 的唯一方法是,如果它是有效的 WordOpenXML,那么您需要使用 InsertXML 方法将其放入文档中。对于任何其他带有格式的 Word 都需要一个转换器。当您使用 Paste 方法、Open 方法打开文件或使用 InsertFile 方法将文件插入文档对象时,Word 会自动触发转换器。
通常,我会使用 FormattedText 属性 将格式化的内容从一个文档传送到另一个文档。但在某些特殊情况下,它不包含所需的内容(例如页眉、页脚、页边距)。那么你确实需要 Copy/Paste.
我觉得Word的粘贴方法应该可以。尝试类似的东西:
newDoc.Content.Paste
或者,因为您使用了激活:
Selection.Paste