9

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

4

2 回答 2

22

这是一个将一些文本写入 word 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();
于 2012-11-08T00:03:41.463 回答
10

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

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

selection.TypeText("\f");
于 2014-03-27T08:49:24.623 回答