我从c#代码中打开了一个word文档(参见下面的代码)。单词文档可以包含任何单词文档(表格、图片等)。关于文件的信息够多了。我想要的是搜索一个特定的标记,然后选择整个单词。
例子:
这可能是我想找到的单词之前的文字!#命令1这可能是我想要找到的单词后面的文本!#Command3 2可能是这里的图片或什么的!#Command3 3
我想选择这3个单词(!#Command3 1,!#Command3 2,!#Command3 3)并将它们添加到列表中。
代码:
public List<string> getListOfCommands()
{
List<string> commandList = new List<string>();
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
object fileName = ofd.FileName;
Word.Application wapp = GetWordApp();
var document = wapp.Documents.Open(fileName);
object findText = "!#"; //Commands tag
wapp.Selection.Find.ClearFormatting();
if(wapp.Selection.Find.Execute(findText))
{
//Add the !#Command to a list here
}
else
{
}
return commandList;
}发布于 2014-08-26 09:48:22
我花了更多的时间在上面,并通过命令中的addind和endTag找到了解决这个问题的方法。
新的守则:
public List<string> getListOfCommands()
{
List<string> commandList = new List<string>();
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
object fileName = ofd.FileName;
Word.Application wapp = GetWordApp();
var document = wapp.Documents.Open(fileName);
var range1 = document.Range();
var range2 = document.Range();
string findTextStart = "!#"; //Commands tagStart
string findTextEnd = "#!"; //Commands tagEnd
wapp.Selection.Find.ClearFormatting();
range1.Find.Execute(findTextStart);
while (range1.Find.Found)
{
if (range1.Text.Contains(findTextStart))
{
range2.Find.Execute(findTextEnd);
if (range1.End < range2.Start)
{
Word.Range temprange = document.Range(range1.End, range2.Start);
commandList.Add(temprange.Text);
}
else
{
commandList.Add("Error - Are you missing a start or end tag?");
}
}
range1.Find.Execute(findTextStart);
}
return commandList;
}https://stackoverflow.com/questions/25499812
复制相似问题