2016-02-09 61 views
2

我想用C#查找文本(組裝)的特定刺痛。我這個小碼所著搜索一個excel文件:C#通過Excel工作簿中搜索

private void button1_Click(object sender, EventArgs e) 
{ 
    string File_name = "C:\\test.xls"; 
    Microsoft.Office.Interop.Excel.Application oXL = new Microsoft.Office.Interop.Excel.Application(); 
    Microsoft.Office.Interop.Excel.Workbook oWB; 
    Microsoft.Office.Interop.Excel.Worksheet oSheet; 
    try 
    { 
     object missing = System.Reflection.Missing.Value; 
     oWB = oXL.Workbooks.Open(File_name, missing, missing, missing, missing, 
      missing, missing, missing, missing, missing, missing, 
      missing, missing, missing, missing); 
     oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oWB.Worksheets[3]; 
     Microsoft.Office.Interop.Excel.Range oRng = GetSpecifiedRange("ASSEMBLY", oSheet); 
     if (oRng != null) 
     { 
      MessageBox.Show("Text found, position is Row:" + oRng.Row + " and column:" + oRng.Column); 
     } 
     else 
     { 
      MessageBox.Show("Text is not found"); 
     } 
     oWB.Close(false, missing, missing); 

     oSheet = null; 
     oWB = null; 
     oXL.Quit(); 
    } 
    catch (Exception ex) 
    { 

    } 
} 
private Microsoft.Office.Interop.Excel.Range GetSpecifiedRange(string matchStr, Microsoft.Office.Interop.Excel.Worksheet objWs) 
{ 
    object missing = System.Reflection.Missing.Value; 
    Microsoft.Office.Interop.Excel.Range currentFind = null; 
    Microsoft.Office.Interop.Excel.Range firstFind = null; 
    currentFind = objWs.get_Range("A1", "AM100").Find(matchStr, missing, 
        Microsoft.Office.Interop.Excel.XlFindLookIn.xlValues, 
        Microsoft.Office.Interop.Excel.XlLookAt.xlPart, 
        Microsoft.Office.Interop.Excel.XlSearchOrder.xlByRows, 
        Microsoft.Office.Interop.Excel.XlSearchDirection.xlNext, false, missing, missing); 
    return currentFind; 

} 

該工程確定,就可以找到工作簿中給定的字符串。但是,該工作簿有很多工作表,現在我只搜索一個(表3)。如何搜索整個工作簿?

另外,這個excel文件有很多次「ASSEMBLY」這個詞。如何繼續搜索並顯示所有結果,而不僅僅是第一個?

+0

您專門詢問表3 ..所以這就是你正在尋找 – Rob

+0

要搜索每個表,迭代他們:'的foreach(Excel.Worksheet片oWB.Worksheets){...}'。要繼續搜索致電'.FindNext' –

+0

希望你的帖子能爲你的問題實現的答案...謝謝 – sam

回答

-1
k = 1; 
do { 
    oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oWB.Worksheets[k]; 
} while (k <= oWB.Worksheets.Count); 
相關問題