从Word Interop文档中删除文本

时间:2016-03-03 21:17:53

标签: c# ms-word office-interop

我在尝试使用Word Interop从Word文档中删除数据/文本列表时遇到问题。到目前为止,我认为我可以通读文档来查找起始文本,然后查找结束文本,并将每个索引保存到自己的变量中。接下来,我将循环遍历从起始索引到结束索引的数据,并删除其间的所有文本。

问题是它工作不正常而且没有提供预期的结果。我不能理解 Scanner in = new Scanner(System.in); System.out.print("Please enter your base: "); int base = in.nextInt(); System.out.print("Please enter your exponent: "); int power = in.nextInt(); int result = mathPower(base, power); System.out.println(base + " to the power of " + power + " is " + result + "."); } public static int mathPower(int a, int b) { int result = a; if (b == 0) { result = 1; } if (b < 0) { a = (1 / a); b = -b; } for (a = 1; a < b; a++) { result = result * a; return result; } return result; } 接口在Range中的工作原理。它删除了一些行但不是全部,似乎超出了我关心删除的段落。我错过了什么?必须有更好的方法来做到这一点。 Interop的文档似乎很少。

document.Paragraphs[i+1].Range.Delete();

2 个答案:

答案 0 :(得分:1)

您尝试的方法的缺点是,开始和结束位置(文档故事开头的字符数)将根据存在的非可见/非打印字符而有所不同。内容控制,字段代码和其他因素会影响这一点 - 所有这些都取决于查询的方式。

更可靠的是将起点存储在一个Range中,然后将其扩展到终点。

我还建议使用Range.Find搜索起点和终点。

Bare-bones伪代码示例,因为我没有足够的信息继续为您提供完整的工作代码:

Word.Range rngToDelete = null;
Word.Range rngFind = document.Content;
bool wasFound = false;
object missing = System.Type.Missing;
object oEnd = Word.WdCollapseDirection.wdCollapseEnd;
wasFound = rngFind.Find.Execute("firstWordImSearchingFor", ref missing, ref missing, 
           ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, 
           ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
if (wasFound)
{
  rngToDelete = rngFind.Duplicate //rngFind is now where the term was found!
  //reset the range to Find so it moves forward
  rngFind.Collapse(ref oEnd);
  rngFind.End = Document.Content.End 
      wasFound = rngFind.Find.Execute("lastWordImSearchingFor", ref missing, ref missing, 
           ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, 
           ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
  if (wasFound)
  {
    rngToDelete.End = rngFind.End;
    rngToDelete.Delete();
  }
}

答案 1 :(得分:0)

这是完全未经测试的,并作为建议提供:

1