Hello,
Thanks for your inquiry!
Kindly note that our Spire.Doc cannot get the index of the word “@key” directly, but can get the TextRange where the “@key” is located.
Please refer to the following code to get the TextRange of the next “@key” from the “@key1” and the number of “@Key” after“@Key1”.
- Code: Select all
//Create word document
Document document = new Document();
//Load the document from disk.
document.LoadFromFile(@"E:\testdoc\key.docx");
//Find key1
TextSelection[] textSelections = document.FindAllString("@key1", false, true);
//get each index of key1 in the para,section,document
int key1TextIndex = 0;
int key1ParaIndex = 0;
int key1SectIndex = 0;
foreach (TextSelection selection in textSelections)
{
Paragraph key1Para = selection.GetAsOneRange().OwnerParagraph;
key1TextIndex = key1Para.GetIndex(selection.GetAsOneRange());
key1ParaIndex = key1Para.OwnerTextBody.GetIndex(key1Para);
key1SectIndex = document.GetIndex(key1Para.OwnerTextBody.Owner);
}
List<int> key = new List<int>(); //save the conform index of "@key"finds
//find key
TextSelection[] keyFinds = document.FindAllString("@key", false, true);
for(int i =0; i < keyFinds.Length; i++)
{
TextSelection keyfind = keyFinds[i];
Paragraph keyFindPara = keyfind.GetAsOneRange().OwnerParagraph;
//key key1 in the same section
if(document.GetIndex(keyFindPara.OwnerTextBody.Owner).Equals(key1SectIndex))
{
//key paragraph under the key1
if(keyFindPara.OwnerTextBody.GetIndex(keyFindPara) > key1ParaIndex)
{
key.Add(i);
}else if (keyFindPara.OwnerTextBody.GetIndex(keyFindPara).Equals(key1ParaIndex)){
//key key1 in the same paragraph, but key textrange under the key1
if (keyFindPara.GetIndex(keyfind.GetAsOneRange()) > key1TextIndex)
{
key.Add(i);
}
}
}
//key section under the key1
else if(document.GetIndex(keyFindPara.OwnerTextBody.Owner) > key1SectIndex)
{
key.Add(i);
}
}
TextRange theFirstKey = keyFinds[key[0]].GetAsOneRange();
int count = key.Count;
If the code does not meet your needs, please describe your needs in detail, and provide us with your input file for reference. Thanks in advance.
Sincerely,
Marcia
E-iceblue support team