c# - 如何使用 word interop 一次将一个项目添加到 word 文档的新行

标签 c# .net ms-word office-interop

我正在尝试将这三种类型的内容添加到 word 文档中。这就是我现在正在尝试的方式。但是,每一项都会取代最后一项。添加图像总是添加到页面的开头。我有一个循环调用一个函数来创建标题和表格,然后添加图像。我认为问题是范围。我使用对象的起始范围 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 方法,该方法:

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.

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

这样,就可以直接向文档中添加新内容。

为了完整起见,我提供了一个示例来展示解决方案的工作原理。该示例通过 for 循环进行循环,并在每次迭代中插入:

  • 新的一行文字
  • 一张 table
  • 一张照片

示例已作为 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();
        }
    }
}

关于c# - 如何使用 word interop 一次将一个项目添加到 word 文档的新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12718044/

相关文章:

c# - 设置 System.Enum 的基础值

c# - 通过 Azure 函数的 SQL 连接仅适用于本地主机

c# - 您可以通过 TcpClient 发送大于 SendBufferSize 的文件吗?

python - 如何用 python 搜索和替换 ms word 文档中所有出现的字符串?

c# - Silverlight 依赖属性未在自定义控件中通知

c# - 不支持的sourceStream NAUDIO

c# - 为什么在运行动态编译的 EXE 时会看到控制台窗口?

.net - .Net 中的 Marshal.DestroyStructure 与 Marshal.FreeHGlobal

c# - Microsoft Word 2007 VSTO,在单词外创建表格?

java - 如何将自定义 XML 存储部分添加到 Word 文档 - 最好使用 docx4j