我正在使用C#和" Microsoft.Office.Interop.Word"创建和格式化word文档。创建之后,我需要能够选择文本的某些行,因此我可以将它们显示为超链接(使用rng.Hyperlinks.Add)。我有一个ArrayList,其中填充了我感兴趣的字符串的开始和结束索引,但是当我尝试使用这些位置来创建一个Range时,它适用于第一个实例但是错误地选择了一个文本字符串。所有其余的文件。
什么可能导致我的document.Content.Text中的给定字符串的位置与文档中的位置之间的差异?是否可以调整我的索引值以补偿这种差异或使用不同的调用获得更正确的索引值? (目前我通过添加到document.Content.Text几次在文档中创建一个部分,然后在我的索引数组中记录document.Content.Text.Length)
该文档的摘录最终看起来像这样,但我改为虚拟数据,并没有保持确切的长度和位置 - 它只包含在视觉中:
代码大致是这样的:
Microsoft.Office.Interop.Word.Application winword = new
Microsoft.Office.Interop.Word.Application();
object missing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);
document.Content.SetRange(0, 0);
int startLocation = 0;
ArrayList startingPositions = new ArrayList();
ArrayList endingPositions = new ArrayList();
//loop that writes to the doc, each iteration create four line sections based
//on data i have in datastructure
for (int i = 0; dataStructure.Length; i++)
{
startingPositions.Add(startLocation);
document.Content.Text += dataStructure.lineOne;
endingPositions.Add(document.Content.Text.Length);
document.Content.Text += dataStructure.otherlineTwo;
document.Content.Text += dataStructure.otherlineThree;
document.Content.Text += dataStructure.otherlineFour + "\n";
startLocation = document.Content.Text.Length;
}
//loop that adds hyperlinks using indexes recorded above
for (int x = 0; x < startingPositions.Count; x++)
{
Range rng = document.Range(startingPositions[x], endingPositions[x]);
rng.Select();
rng.Hyperlinks.Add(rng, urls[x], ref missing, ref missing, ref missing, ref missing);
}
答案 0 :(得分:0)
MS Office中的数组从1开始而不是从0开始。
答案 1 :(得分:0)
因此,存在一个问题,即创建超链接会像我描述的那样混乱索引,但是在这种情况下,您可以通过在创建超链接时向后循环来解决此问题,因此索引不会对该位置产生影响。
所以我的最后一个循环变成了这个:
//looping backwards using x-- now
for (int x = startingPositions.Count - 1; x >= 0; x--)
{
Range rng = document.Range(startingPositions[x], endingPositions[x]);
rng.Select();
rng.Hyperlinks.Add(rng, urls[x], ref missing, ref missing, ref missing, ref missing);
}