我正在尝试将这三种类型的内容添加到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方法:@H_403_3@
Returns a Paragraph object that represents a new,blank paragraph
added to a document. (…) If Range isn’t specified,the new paragraph is added after the selection or range or at the end of the document.@H_403_3@
资料来源:http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.paragraphs.add(v=office.14).aspx@H_403_3@
通过这种方式,它可以直接将新内容附加到文档中.@H_403_3@
为了完整起见,我提供了一个示例,说明了解决方案的工作原理.该示例循环遍历for循环,并且每次迭代都会插入:@H_403_3@
>一个新的文本行
>一张桌子
>一张照片@H_403_3@
该示例已实现为C#控制台应用程序,使用:@H_403_3@
> .NET 4.5
> Microsoft Office对象库版本15.0和
> Microsoft Word对象库15.0版@H_403_3@
…即MS Office 2013附带的MS Word Interop API.@H_403_3@
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(); } } }