How to read MS Word paragraph and table content line by line

爷,独闯天下 提交于 2019-12-03 21:31:31

Using selection for scaning a document should be quite expensive in performance. I would suggest the following code:

        List<Word.Range> TablesRanges = new List<Word.Range>();

        wordApp = new Microsoft.Office.Interop.Word.Application();
        doc = wordApp.Documents.OpenNoRepairDialog(FileName: @"c:\AAAAA.docx", ConfirmConversions: false, ReadOnly: true, AddToRecentFiles: false, NoEncodingDialog: true);


        for (int iCounter = 1; iCounter <= doc.Tables.Count; iCounter++)
        {
            Word.Range TRange = doc.Tables[iCounter].Range;
            TablesRanges.Add(TRange);
        }

        Boolean bInTable;
        for (int par = 1; par <= doc.Paragraphs.Count; par++)
        {
            bInTable = false;
            Word.Range r = doc.Paragraphs[par].Range;
            foreach (Word.Range range in TablesRanges)
            {
                if (r.Start >= range.Start && r.Start <= range.End)
                {
                    Console.WriteLine("In Table - Paragraph number " + par.ToString() + ":" + r.Text);
                    bInTable = true;
                    break;
                }

            }

            if (!bInTable)
                Console.WriteLine("!!!!!! Not In Table - Paragraph number " + par.ToString() + ":" + r.Text);
        }

I found a workaround for the same. Approach is listed below.

1. Open the Word Document using WordApp.Documents.Open()
2. Using Selection.MoveDown to traverse the Document line by line
3. Skipping the content of the Table's Cells
4. At last processing only Tables of the document

//Process all Paragraphs in the documents
while (doc.ActiveWindow.Selection.Bookmarks.Exists(@"\EndOfDoc") == false)
{
  doc.ActiveWindow.Selection.MoveDown(ref wdLine, ref wdCountOne, ref wdMove);
  doc.ActiveWindow.Selection.HomeKey(ref wdLine, ref wdMove);

  //Skiping table content
  if (doc.ActiveWindow.Selection.get_Information(WdInformation.wdEndOfRangeColumnNumber).ToString() != "-1")
  {
    while (doc.ActiveWindow.Selection.get_Information(WdInformation.wdEndOfRangeColumnNumber).ToString() != "-1")
    {
      if (doc.ActiveWindow.Selection.Bookmarks.Exists(@"\EndOfDoc"))
        break;

      doc.ActiveWindow.Selection.MoveDown(ref wdLine, ref wdCountOne, ref wdMove);
      doc.ActiveWindow.Selection.HomeKey(ref wdLine, ref wdMove);
    }
    doc.ActiveWindow.Selection.HomeKey(ref wdLine, ref wdMove);
  }

  doc.ActiveWindow.Selection.EndKey(ref wdLine, ref wdExtend);
  currLine = doc.ActiveWindow.Selection.Text;
}

//Processing all tables in the documents
for (int iCounter = 1; iCounter <= doc.Tables.Count; iCounter++)
{
  foreach (Row aRow in doc.Tables[iCounter].Rows)
  {
    foreach (Cell aCell in aRow.Cells)
    {
      currLine = aCell.Range.Text;
      //Process Line
    }
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!