3

我正在尝试根据用户在 ComboBox 元素上所做的选择来选择 Excel 工作表,但这是我唯一的解决方案,而且很丑:

using (var package = new ExcelPackage(existingFile))
{
    ExcelWorkbook workbook = package.Workbook;
    if (workbook != null)
    {
        if (workbook.Worksheets.Count > 0)
        {
            ExcelWorksheet currentWorkSheet;

            if (blYear.Text == "2010")
            {
                currentWorkSheet = workbook.Worksheets.First();
            }
            else if (blYear.Text == "2011")
            {
                currentWorkSheet = workbook.Worksheets[2];
            }
            else if (blYear.Text == "2012")
            {
                currentWorkSheet = workbook.Worksheets[3];
            }
            else if (blYear.Text == "2013")
            {
                currentWorkSheet = workbook.Worksheets[4];
            }
            else
            {
                currentWorkSheet = workbook.Worksheets.First();
            }
        }
    }
}

可以从 ComboBox 中获取选定的 Item 索引并改进我的代码吗?否则,每次 Excel 获得新工作表时,我都需要触摸代码,而我不想要这个。有什么帮助吗?建议?解决方案?

4

2 回答 2

3

尝试使用ComboBox.SelectedIndex属性。

int i = blYear.SelectedIndex;
currentWorkSheet = workbook.WorkSheets[i + 1]; 

//The VSTO library uses one-based arrays for some reason, and .SelectedIndex 
//uses the standard zero-based ones. Hence the "+ 1".

我目前无法自己测试,但这是我想到的第一件事。


if, else if, else if, else if...作为使用相同对象执行此类语句的附带说明,您可以改用switch/case语句。

例子:

switch (blYear.Text)
{
       case "2010":
           currentWorkSheet = workbook.Worksheets.First();
           break;
       case "2011":
           currentWorkSheet = workbook.Worksheets[2];
           break;
       case "2012":
           currentWorkSheet = workbook.Worksheets[3];
           break;
       case "2013":
           currentWorkSheet = workbook.Worksheets[4];
           break;
       default:
           currentWorkSheet = workbook.Worksheets.First();
           break;
}
于 2013-05-05T19:49:18.993 回答
0

这对我有用。

using Excel = Microsoft.Office.Interop.Excel;
public class Form1 {

    private void Form1_Load(object sender, System.EventArgs e) {
        Excel.Application oXL = new Excel.Application();
        Excel.Workbook oWB = oXL.Workbooks.Open("C:\\your_path_here\\your_file.xls");
        oXL.Visible = true;
        foreach (Excel.Worksheet oSheet in oWB.Sheets) {
            ComboBox1.Items.Add(oSheet.Name);
        }

        ComboBox1.SelectedIndex = 0;
    }
}
于 2018-01-26T01:41:59.317 回答