Excel工作表添加问题c#

本文关键字:问题 添加 工作 Excel | 更新日期: 2023-09-27 18:08:47

我遇到的问题是,每次从组合框中选择一个数字时,它正在创建一个新的工作表。我只想将变量仅添加到活动工作表中,而不是每次都创建工作表。如有任何帮助,不胜感激。

这样的东西可以工作吗?

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

Excel工作表添加问题c#

把这段代码提出来,不要在每次选择时都调用它。你可以移动它,使它只执行一次。

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