3

我一直在尝试以下代码来使用 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 个字符

4

2 回答 2

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();
}
于 2013-04-05T15:16:37.280 回答
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;

参考:

于 2013-04-05T21:38:43.340 回答