Excel工作表添加问题C#

我遇到的问题是,每次从combobox中select一个数字,它正在创build一个新的工作表。 我只想将variables添加到活动工作表,而不是每次创build工作表。 任何帮助是极大的赞赏。

会这样的工作吗?

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"; } 

分解此代码,不要为每个select调用它。 您可以移动它,以便它只执行一次。

  // 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); }