2016-10-06 61 views
0

此處的代碼在我的列表框(employeebox)中獲取一個名稱並刪除該工作表上的整個行。這工作,沒有錯誤..我的問題是,我有19個不同的表需要檢查,但我只能用此代碼一次檢查1 ..「Excel.Worksheet xlWorkSheet =(Excel.Worksheet)xlWorkBook .Worksheets [2];「..有沒有什麼辦法可以在刪除按鈕被點擊後檢查所有的表格?我非常感謝任何人的幫助。在Excel中搜索多個工作表C#

private void delete_Click(object sender, EventArgs e) 
{ 
    //create excel 
    Excel.Application xlexcel = new Excel.Application(); 
    Excel.Workbook xlWorkBook = xlexcel.Workbooks.Open(@"C:\\SAMPLE.xlsx"); 
    Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets[2]; 

    //search within excel 
    Excel.Range usedRanage = xlWorkSheet.UsedRange; 
    foreach (Excel.Range row in usedRanage) 
    { 
     //grab name once selected in box 
     if (employeeBox.SelectedItem.Equals(row.Value)) 
     { 
      row.EntireRow.Delete(Excel.XlDeleteShiftDirection.xlShiftUp); 

      MessageBox.Show("Employee Deleted."); 
     } 

    } 

    xlexcel.DisplayAlerts = false; 

    xlWorkBook.SaveAs("C:\\SAMPLE.xlsx", Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, 
    Type.Missing, false, false, Excel.XlSaveAsAccessMode.xlNoChange, 
    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); 

    xlWorkBook.Close(); 
    xlexcel.Quit(); 

    releaseObject(xlexcel); 
    releaseObject(xlWorkBook); 
    releaseObject(xlWorkSheet); 
} 
+1

什麼是錯的,從表去片? –

+0

你好,我只是一個有趣的編碼器......你將不得不循環通過工作簿中的所有現有工作表......像...... foreach(工作簿中的Excel.Worksheet工作表) – JohnG

+0

@DangerZone - 太多的代碼。 –

回答

0
private void delete_Click(object sender, EventArgs e) 
    { 
     //create excel 
     Excel.Application xlexcel = new Excel.Application(); 
     Excel.Workbook xlWorkBook = xlexcel.Workbooks.Open(@"C:\\SAMPLE.xlsx"); 
     int[] Cols = { 1 }; 
     Excel.Range curRange; 

     foreach (Excel.Worksheet sheet in xlWorkBook.Worksheets) 
     { 
      foreach (Excel.Range row in sheet.UsedRange.Rows) 
      { 
       foreach (int c in Cols) 
       { 
        curRange = (Excel.Range)row.Cells[1, 1]; 
        if (curRange.Cells.Value != null) 
        {  
         if (employeeBox.SelectedItem.Equals(sheet.Cells[row.Row, c].Value.ToString())) 
         { 
          row.EntireRow.Delete(Excel.XlDeleteShiftDirection.xlShiftUp); 

          MessageBox.Show("Employee Deleted."); 
         } 
        } 
       } 
      } 
     } 
      xlexcel.DisplayAlerts = false; 

      xlWorkBook.SaveAs("C:\\SAMPLE.xlsx", Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, 
      Type.Missing, false, false, Excel.XlSaveAsAccessMode.xlNoChange, 
      Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); 

      xlWorkBook.Close(); 
      xlexcel.Quit(); 

      releaseObject(xlexcel); 
      releaseObject(xlWorkBook); 


    } 
+0

This works ..通過所有表格,然後刪除我選擇的一個。 –