如何在创建MS Word文档时插入分页符

时间:2012-11-07 19:31:11

标签: c# asp.net ms-word

我尝试通过C#创建Word文档。我希望能够在我的代码中的某个位置插入分页符,但是我不确定如何执行此操作。我主要使用StringBuilder来创建html。 这是在Visual Studio 2010中用c#完成的。我看过一些指南,但大多数都使用像“Word变量”这样的代码。所以我不确定“Word”是来自额外下载的库还是不是。

2 个答案:

答案 0 :(得分:17)

以下是将一些文字写入单词doc然后添加分页符的示例。然后将其余部分写入文档的文本中。为了获得更好的答案,您可能需要重写您的问题,因为您不清楚何时要插入中断以及如何将信息写入文档。我假设了许多永远不会好的东西。

using Word = Microsoft.Office.interop.Word; 

//create a word app
Word._Application  wordApp = new Word.Application();
//add a page
Word.Document doc = wordApp.Documents.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value);
//show word
wordApp.Visible = true;
//write some tex
doc.Content.Text = "This is some content for the word document.\nI am going to want to place a page break HERE ";
//inster a page break after the last word
doc.Words.Last.InsertBreak(Word.WdBreakType.wdPageBreak);
//add some more text
doc.Content.Text += "This line should be on the next page.";
//clean up
Marshal.FinalReleaseComObject(wordApp);
Marshal.FinalReleaseComObject(doc);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

答案 1 :(得分:7)

如果选择了要插入分页符的位置(通过Word.Selection):

最简单的方法是插入以下代码:

selection.TypeText("\f");
相关问题