3

I have been trying the following code to get the first line or first 20 characters of a paragraph using Microsoft office interop word 12

Microsoft.Office.Interop.Word.Application w = new  Microsoft.Office.Interop.Word.Application();
    Microsoft.Office.Interop.Word.Document doc;
    int iParaStart = Para.Range.Start;
    Para.Range.Text = "A big Paragraph Comes here …….";
    Para = doc.Paragraphs.Add();
    int iParaEnd = Para.Range.End; 
  // to select the first sentance code tried       
  doc.Range(iRangeStart,iRangeEnd).Sentences.First.Select();
doc.Range(iRangeStart,iRangeEnd).Sentences.First.Shading.BackgroundPatternColor=WdColor.wdColorOrange;
 // to get the characters code tried
 doc.Range(iRangeStart,iRangeStart+20).Select();

It seems like not working How can i do this . I need to select the either first sentence or first 20 characters

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Jpaul
  • 278
  • 2
  • 11
  • 26
  • 2
    If you're using this code in a long running application or working with many files, this link (http://stackoverflow.com/questions/158706/how-to-properly-clean-up-excel-interop-objects/158752#158752) will help with hanging Office processes (Same issues applies to Word as to Excel) – jordanhill123 Apr 05 '13 at 07:31
  • First off all thank you for the reply, and I am sorry because I am not an expert to go that much deep. I am not dealing with hanging office process now . Just trying to select the first sentence or first 20 char of a paragraph.. – Jpaul Apr 05 '13 at 09:03

2 Answers2

1

Try using (i assumed you have properly open application and word document):

// get paragraph range
paragraphs = doc.Paragraphs;
Word.Paragraph paragraph = paragraphs.First;
Word.Range paragraphRange = paragraph.Range;

Selecting first sentence:

Word.Sentences sentences = paragraphRange.Sentences;
Word.Range firstSentence = sentences.First;
firstSentence.Select();

Selecting first 20 characters:

if (paragraphRange.Text.Length > 20)
{
    Word.Range range = paragraph.Range.Duplicate;
    range.SetRange(range.Start, range.Start + 20);
    range.Select();
}
tinamou
  • 2,282
  • 3
  • 24
  • 28
1

Using the following namespace:

using Microsoft.Office.Interop.Word;

... and given a Document instance:

var wordApplication = new Application();
var myDocument = wordApplication.Documents.Open(@"C:\Users\...\my.docx");

... you can select the first 20 chars of a paragraph like this:

var substring = myDocument.Paragraphs.First.Range.Text.Substring(0, 20);

... and you can select the first line like this:

var firstLine = myDocument.Paragraphs.First.Range.Sentences.First.Text;

References:

Lasse Christiansen
  • 10,205
  • 7
  • 50
  • 79
  • Thank you for the Answer and i have got the answer from the previous post and I tried your code also it also works. – Jpaul Apr 08 '13 at 05:10