使用Microsoft Word互操作的C#程序

时间:2018-12-03 06:09:58

标签: c# ms-word

Word文档:word.doc

One

Two

three

使用Microsoft Word互操作的C#程序

 using System;
 using Microsoft.Office.Interop.Word;

 class Program
 {
   static void Main()
 {
    // Open a doc file.
    Application application = new Application();
    Document document = application.Documents.Open("C:\\word.doc");

    // Loop through all words in the document.
    int count = document.Words.Count;
    for (int i = 1; i <= count; i++)
    {
        // Write the word.
        string text = document.Words[i].Text;
        Console.WriteLine("Word {0} = {1}", i, text);
    }
    // Close word.
    application.Quit();
  }
  }

输出:

Word 1 = One
Word 2 =
Word 3 = Two
Word 4 =
Word 5 = three
Word 6 =

1 个答案:

答案 0 :(得分:1)

尝试一下-为real个单词添加了另一个计数器

    internal class Program
    {
        private static void Main(string[] args)
        {
            // Open a doc file.
            Application application = new Application();
            Document document = application.Documents.Open("C:\\temp\\word.doc");

            // Loop through all words in the document.

            int k = 1;

            int count = document.Words.Count;
            for (int i = 1; i <= count; i++)
            {
                // Write the word.
                string text = document.Words[i].Text.Trim();

                if (!string.IsNullOrEmpty(text))
                {
                    Console.WriteLine("Word {0} = {1}", k, text);
                    k++;
                }
            }

            Console.ReadLine();
            // Close word.
            application.Quit();
        }