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



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 =

试试这个-为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();
}

最新更新