2011-09-14 88 views
1

我遇到的問題是,每次從comboBox中選擇一個數字時,它都會創建一個新的工作表。我只想將變量添加到活動工作表中,而不是每次都創建工作表。任何幫助是極大的讚賞。Excel工作表添加問題C#

會這樣的工作?

 var xl = new Excel.Application(); 
     xl.Visible = true; 
     var wb = (Excel._Workbook)xl.ActiveWorkbook; //(xl.Workbooks.Add(Missing.Value)); 
     var sheet = (Excel._Worksheet)wb.ActiveSheet; 

     //Generate Linear Guide Support in Solidworks 
     if (comboBox1.Text == "0") 
     { 
      sheet.Cells[6, 4] = "0"; //Cell Location[y-axis, x-axis] 
     } 
     if (comboBox2.Text == "AH") 
     { 
      sheet.Cells[6, 5] = "AH"; 
     } 
     if(comboBox3.Text == "2") 
     { 
      sheet.Cells[6, 6] = "2"; 
     }   
+0

我要使用現有的工作簿,並已經將這些值如果可能的話 –

回答

2

將此代碼分解出來,並且不會爲每個選擇調用它。您可以移動它以便它只執行一次。

// Available at the class level. single instance - Singleton pattern may be employed 
    // Check the correct datatype for ExcelSheet 
    ExcelSheet sheet; 
    void UpdateExcelSheet(int row, int col, string value) 
    { 
     if (sheet == null) 
     { 
      var xl = new Excel.Application(); 
      xl.Visible = true; 
      var wb = (Excel._Workbook)(xl.Workbooks.Add(Missing.Value)); 
      sheet = (Excel._Worksheet)wb.ActiveSheet; 
     } 
     sheet.Cells[row, col] = value; 
    } 

    void OnComboSelection() 
    { 
     int row, col; 
     string value; 
     if(comboBox5.Text == "1") 
     { 
      row = 6; col = 6; value = "1"; 
     } 
     if (comboBox3.Text == "2") 
     { 
      row = 6; col = 8; value = "2"; 
     } 
     UpdateExcelSheet(row, col, value); 
    } 
+0

改變我已經有一個表目前我只是想改變 –

+0

要調用workbooks.add當前工作表上()每次連擊框值的變化,導致添加新的工作表 –

+0

有什麼辦法可以添加兩個相同的工作表,而不是添加工作表? –