2016-07-14 61 views
0

我一直在尝试从word文档中删除特定行。逻辑是,如果我在文档中找到特定的单词,我需要删除包含该单词的特定行。到目前为止,我只写了逻辑来找到这个词。但是,追踪行号和删除行,我无法做到。搜索了很多我多个网站,但是,我现在很困惑。你能帮我解决这个问题吗?下面删除MS Word文档中的特定行

是我的代码: -

void searchText(string txt) 
     { 
      Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application(); 
      Microsoft.Office.Interop.Word.Document doc = app.Documents.Open("C:\\Users\\SS5014874\\Desktop\\testdoc1.docx"); 
      object missing = System.Reflection.Missing.Value; 
      doc.Content.Find.ClearFormatting(); 
      object keyword = txt.ToString(); 
      if (doc.Content.Find.Execute(ref keyword, 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)) 
      { 
       //Need the logic to delete the line here 
      } 
      else 
      { 
       MessageBox.Show("Not found"); 
      } 
      doc.Close(ref missing, ref missing, ref missing); 
      app.Quit(ref missing, ref missing, ref missing);    
     } 

请让我知道如果你需要的任何其他信息。

注意:搜索关键字是由文本框给出的,并且上述功能是通过按钮调用的。

+0

检查,如果这有助于http://www.codeproject.com/Questions/519686/deleteplusapluslineplusinpluswordplusfromplusVB-ne – Dandy

+0

@ Dandy-感谢您的答复,然而,这种解决方案对于VB,不适用于C# – Sourav

+0

http://converter.telerik.com/将为你做它 – Dandy

回答

2

喜欢的东西

var range = doc.Content; 
if (range.Find.Execute(txt)) 
{ 
    range.Expand(WdUnits.wdLine); // or change to .wdSentence or .wdParagraph 
    range.Delete(); 
} 
+0

它的工作。唯一的变化是.wdLine而不是.wdParagraph。非常感谢你。 – Sourav

1

您可以迭代文档的段落,然后在特定段落中找到单词后,可以删除该段落。

newDocument = wordApplication.Documents.Open(fileDoc, 
                confirmConversions: false, 
                addToRecentFiles: false, 
                readOnly: true, 
                passwordDocument: Password) 

var docRange = newDocument .Content; 

foreach(var para in docRange.Paragraphs) 
{ 
    if(para.ToString().Contains("word")) 
    { 
    docRange.Delete(para); 
    } 
}