有没有一种方法可以逐行阅读Word文档?

3

我试图提取Word文档中的所有单词。我可以按以下方式一次性完成...

Word.Application word = new Word.Application();
doc = word.Documents.Open(@"C:\SampleText.doc");
doc.Activate();

foreach (Word.Range docRange in doc.Words) // loads all words in document
{
    IEnumerable<string> sortedSubstrings = Enumerable.Range(0, docRange.Text.Trim().Length)
        .Select(i => docRange.Text.Substring(i))
        .OrderBy(s => s.Length < 3 ? s : s.Remove(2, Math.Min(s.Length - 2, 2)));

    wordPosition =
        (int)
        docRange.get_Information(
            Microsoft.Office.Interop.Word.WdInformation.wdFirstCharacterColumnNumber);

    foreach (var substring in sortedSubstrings)
    {
        index = docRange.Text.IndexOf(substring) + wordPosition;
        charLocation[index] = substring;
    }
}

然而,我更希望能够逐行加载文档...这样做可能吗?

我可以按段落加载它,但是我无法迭代遍历段落以提取所有单词。

foreach (Word.Paragraph para in doc.Paragraphs)
{
    foreach (Word.Range docRange in para) // Error: type Word.para is not enumeranle**
    {
        IEnumerable<string> sortedSubstrings = Enumerable.Range(0, docRange.Text.Trim().Length)
            .Select(i => docRange.Text.Substring(i))
            .OrderBy(s => s.Length < 3 ? s : s.Remove(2, Math.Min(s.Length - 2, 2)));

        wordPosition =
            (int)
            docRange.get_Information(
                Microsoft.Office.Interop.Word.WdInformation.wdFirstCharacterColumnNumber);

        foreach (var substring in sortedSubstrings)
        {
            index = docRange.Text.IndexOf(substring) + wordPosition;
            charLocation[index] = substring;
        }

    }
}
4个回答

3
这有助于您逐行获取字符串。
    object file = Path.GetDirectoryName(Application.ExecutablePath) + @"\Answer.doc";

    Word.Application wordObject = new Word.ApplicationClass();
    wordObject.Visible = false;

    object nullobject = Missing.Value;
    Word.Document docs = wordObject.Documents.Open
        (ref file, ref nullobject, ref nullobject, ref nullobject,
        ref nullobject, ref nullobject, ref nullobject, ref nullobject,
        ref nullobject, ref nullobject, ref nullobject, ref nullobject,
        ref nullobject, ref nullobject, ref nullobject, ref nullobject);

    String strLine;
    bool bolEOF = false;

    docs.Characters[1].Select();

    int index = 0;
    do
    {
        object unit = Word.WdUnits.wdLine;
        object count = 1;
        wordObject.Selection.MoveEnd(ref unit, ref count);

        strLine = wordObject.Selection.Text;
        richTextBox1.Text += ++index + " - " + strLine + "\r\n"; //for our understanding

        object direction = Word.WdCollapseDirection.wdCollapseEnd;
        wordObject.Selection.Collapse(ref direction);

        if (wordObject.Selection.Bookmarks.Exists(@"\EndOfDoc"))
            bolEOF = true;
    } while (!bolEOF);

    docs.Close(ref nullobject, ref nullobject, ref nullobject);
    wordObject.Quit(ref nullobject, ref nullobject, ref nullobject);
    docs = null;
    wordObject = null;

这里是代码背后的天才。点击链接获取更多关于它如何运作的解释。

运行了这段代码,但不幸陷入了一个无限循环。我不知道为什么。 - Bat_Programmer
不知道这是哪个版本的Word?通过搜索书签来确保存在名为“EndOfDoc”的书签。通常,默认情况下,每个文档的末尾都会有这个书签。 - nawfal

2

我建议在这个页面上遵循代码这里

关键是使用Word.ApplicationClass(Microsoft.Interop.Word)对象读取它,尽管他从哪里获取“Doc”对象超出了我的理解。我会假设你用ApplicationClass创建它。

编辑:通过调用此方法检索文档:

Word.Document doc = wordApp.Documents.Open(ref file, ref nullobj, ref nullobj,
                                      ref nullobj, ref nullobj, ref nullobj,
                                      ref nullobj, ref nullobj, ref nullobj,
                                      ref nullobj, ref nullobj, ref nullobj);

遗憾的是,我链接的页面上的代码格式并不容易处理。

编辑2:从那里,您可以循环遍历文档段落,但据我所见,没有办法循环遍历行。建议使用一些模式匹配来查找换行符。

为了从段落中提取文本,请使用Word.Paragraph.Range.Text,这将返回段落内所有文本。然后您必须搜索换行符。我会使用string.IndexOf()

或者,如果您想逐句提取行,则可以简单地迭代Range.Sentences


很不幸,我无法在vs2010中使用Word.ApplicationClass(Microsoft.Interop.Word)类。:( 所以上面的代码不起作用... 我需要的是使Word.Paragraph para在doc.Paragraphs中可枚举.. 你能帮忙吗!!! - Fraiser
我已经修改了我的答案,以向您展示如何遍历句子。逐行遍历文件是不可能的,因为每行有多少个字符完全取决于页面设置。您可以获取页面的宽度和高度,然后使用这些信息来读取一定数量的字符,但这似乎需要很大的努力。您需要这段代码做什么? - Nick Udell

0
        Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
        object miss = System.Reflection.Missing.Value;
        object path = @"D:\viewstate.docx";
        object readOnly = true;
        Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
        string totaltext = "";

        object unit = Microsoft.Office.Interop.Word.WdUnits.wdLine;
        object count = 1;
        word.Selection.MoveEnd(ref unit, ref count);
        totaltext = word.Selection.Text;

        TextBox1.Text = totaltext;
        docs.Close(ref miss, ref miss, ref miss);
        word.Quit(ref miss, ref miss, ref miss);
        docs = null;
        word = null;

对每一行进行计数增加


0
我推荐使用DocX库。它很轻量级,不需要在机器上安装Word。以下是用于逐行获取文本的代码:
using(DocX doc = DocX.Load("sample.docx"))
{
     for (int i = 0; i < doc.Paragraphs.Count; i++ )
     {
          foreach (var item in doc.Paragraphs[i].Text.Split(new string[]{"\n"}
                    , StringSplitOptions.RemoveEmptyEntries))
          {
                Console.WriteLine(item);
          }
     }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接