【问题标题】:C# program that uses Microsoft Word interop使用 Microsoft Word 互操作的 C# 程序
【发布时间】:2018-12-03 14:35:40
【问题描述】:

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 =

【问题讨论】:

  • 欢迎来到stackoverflow。请花一分钟时间回答tour,尤其是How to Askedit 您的问题。
  • 这似乎有效 - 有什么问题?
  • 我猜你的问题是为什么输出显示 6 个单词而文档中只有 3 个单词。如果我是对的,那是因为每个单词后面都有一个输入。您可以通过将 document.Words[i].Text 与 Empty 和 Null 进行比较来忽略它。

标签: c# ms-word


【解决方案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();
        }

【讨论】:

  • 当我们得到文本变量集时也做了一个Trim()
猜你喜欢
  • 2020-11-10
  • 1970-01-01
  • 2021-10-20
  • 1970-01-01
  • 2016-03-07
  • 2011-07-15
  • 2010-11-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多