如何使用Microsoft Office Interop word选择段落的第一行或(前20个字符)。

时间:2013-04-05 07:14:59

标签: c# winforms ms-word office-interop

我一直在尝试以下代码,使用Microsoft office interop word 12获取段落的第一行或前20个字符

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();

似乎无法正常工作我该怎么办?我需要选择第一个句子或前20个字符

2 个答案:

答案 0 :(得分:1)

尝试使用(我假设您已正确打开应用程序和word文档):

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

选择第一句话:

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

选择前20个字符:

if (paragraphRange.Text.Length > 20)
{
    Word.Range range = paragraph.Range.Duplicate;
    range.SetRange(range.Start, range.Start + 20);
    range.Select();
}

答案 1 :(得分:1)

使用以下命名空间:

using Microsoft.Office.Interop.Word;

...并给出Document个实例:

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

...你可以选择这样一个段落的前20个字符:

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

...你可以像这样选择第一行:

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

参考文献: