如何使用word interop一次一个地添加项目到word文档的新行

我正在尝试将这三种类型的内容添加到word doc中。 这就是我现在尝试这样做的方式。 但是,每个项目都会替换最后一个项目。 添加图像始终会添加到页面的开头。 我有一个循环调用函数来创建标题和表,然后添加图像。 我认为问题是范围。 我使用对象start = 0的起始范围;

如何让这些一次添加一个到文档中的新行?

foreach (var category in observedColumns) { CreateHeadersAndTables(); createPictures(); } 

添加标题:

  object start = 0; Word.Range rng = doc.Range(ref start , Missing.Value); Word.Paragraph heading; heading = doc.Content.Paragraphs.Add(Missing.Value); heading.Range.Text = category; heading.Range.InsertParagraphAfter(); 

添加表格:

  Word.Table table; table = doc.Content.Tables.Add(rng, 1, 5); 

添加图片:

  doc.Application.Selection.InlineShapes.AddPicture(@path); 

一种简单的方法是使用段落来处理Range对象,并简单地逐个插入一个新段落。

查看API文档显示Paragraphs实现了一个Add方法:

返回Paragraph对象,该对象表示添加到文档的新空白段落。 (…)如果未指定Range,则在选择或范围之后或文档末尾添加新段落。

来源: http : //msdn.microsoft.com/en-us/library/microsoft.office.interop.word.paragraphs.add(v = office.14).aspx

通过这种方式,它可以直接将新内容附加到文档中。

为了完整起见,我提供了一个示例,说明了解决方案的工作原理。 该示例循环遍历for循环,并且每次迭代都会插入:

  • 一个新的文本行
  • 一张桌子
  • 照片

该示例已实现为C#控制台应用程序,使用:

  • .NET 4.5
  • Microsoft Office对象库15.0版和
  • Microsoft Word对象库15.0版

…即MS Office 2013附带的MS Word Interop API。

 using System; using System.IO; using Microsoft.Office.Interop.Word; using Application = Microsoft.Office.Interop.Word.Application; namespace StackOverflowWordInterop { class Program { static void Main() { // Open word and a docx file var wordApplication = new Application() { Visible = true }; var document = wordApplication.Documents.Open(@"C:\Users\myUserName\Documents\document.docx", Visible: true); // "10" is chosen by random - select a value that fits your purpose for (var i = 0; i < 10; i++) { // Insert text var pText = document.Paragraphs.Add(); pText.Format.SpaceAfter = 10f; pText.Range.Text = String.Format("This is line #{0}", i); pText.Range.InsertParagraphAfter(); // Insert table var pTable = document.Paragraphs.Add(); pTable.Format.SpaceAfter = 10f; var table = document.Tables.Add(pTable.Range, 2, 3, WdDefaultTableBehavior.wdWord9TableBehavior); for (var r = 1; r <= table.Rows.Count; r++) for (var c = 1; c <= table.Columns.Count; c++) table.Cell(r, c).Range.Text = String.Format("This is cell {0} in table #{1}", String.Format("({0},{1})", r,c) , i); // Insert picture var pPicture = document.Paragraphs.Add(); pPicture.Format.SpaceAfter = 10f; document.InlineShapes.AddPicture(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "img_1.png"), Range: pPicture.Range); } // Some console ascii-UI Console.WriteLine("Press any key to save document and close word.."); Console.ReadLine(); // Save settings document.Save(); // Close word wordApplication.Quit(); } } }