使用C#将特定页面从一个word文档复制到另一个word文档

时间:2014-07-08 14:49:34

标签: c# c#-4.0 ms-word office-interop

我已经通过这里的论坛使用C#将一个word文档的内容复制到另一个word文档中。 Copy text from word file to a new word

我使用了第二种解决方案。 这部分负责复制整个文档以及格式化

static MSWord.Document CopyToNewDocument(MSWord.Document document)
{
document.StoryRanges[MSWord.WdStoryType.wdMainTextStory].Copy();
var newDocument = document.Application.Documents.Add();
newDocument.StoryRanges[MSWord.WdStoryType.wdMainTextStory].Paste();
return newDocument;
}

现在我想指定一个来自用户的页面范围,例如起始页码和&结束页码,并将所选范围单独复制到另一个Word文档,同时保留格式。 任何帮助都将受到高度赞赏.....

1 个答案:

答案 0 :(得分:2)

您可能需要查看http://social.msdn.microsoft.com/Forums/office/en-US/e48b3126-941d-490a-85ee-e327bbe7e81b/convert-specific-word-pages-to-pdf-in-c?forum=worddev

它显示了如何从word文档中获取特定范围的页面(保留格式)。

相关部分(如果链接页面消失):

打开一个单词实例。

  Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();

然后加载您的文档。打开文件后,您必须为您的选择准备范围。 Count和count2是您在特殊情况下提供的页码。

  object what = WdGoToItem.wdGoToPage;
  object which = WdGoToDirection.wdGoToFirst;
  object count = 1;
  Range startRange = word.Selection.GoTo(ref what, ref which, ref count, ref oMissing);
  object count2 = (int)count + 3;
  Range endRange = word.Selection.GoTo(ref what, ref which, ref count2, ref oMissing);
  endRange.SetRange(startRange.Start, endRange.End - 1);
  endRange.Select();

Selection.Copy()然后将所选页面复制到剪贴板,同时保留格式。

  word.Selection.Copy();

源的其余部分会创建一个新文档,您可以在其中粘贴选择。

  word.Documents.Add();
  word.Selection.Paste();

  object outputFileName = "d:\\test1.doc";
  object fileFormat = WdSaveFormat.wdFormatDocument97;

  word.ActiveDocument.SaveAs(ref outputFileName,
      ref fileFormat, ref oMissing, ref oMissing,
      ref oMissing, ref oMissing, ref oMissing, ref oMissing,
      ref oMissing, ref oMissing, ref oMissing, ref oMissing,
      ref oMissing, ref oMissing, ref oMissing, ref oMissing);

我希望这有点帮助。