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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13276821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:02:47  来源:igfitidea点击:

How to insert Page break when creating MS Word document

c#asp.netms-word

提问by john

I trying to create a Word document via C#. I want to be able to insert a page break at a certain point in my code, however I am not sure on how to do this. I am mostly using StringBuilder to create the html. This is being done in Visual studios 2010 with c#. I've looked at some guides but most of them use code like "Word variable". So I'm not sure if "Word" comes from an extra downloaded library or what not.

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

采纳答案by Sorceri

Here is an example of writing some text to the word doc then adding a page break. Then writing the rest to the text to the document. In order to get a better answer you may need to rewrite your question as it is unclear when you want to insert a break and how you are writing the information to the document. I am assuming a lot which is never good.

这是将一些文本写入单词 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();

回答by user3165438

If the location you would like to insert the page break is selected (by Word.Selection) :

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

The easiest way is to insert there the following code:

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

selection.TypeText("\f");