2016-07-14 43 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); 
    } 
}