我正在尝试根据用户在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获取新工作表时我都需要触摸代码,我不想这样做。有帮助吗?建议?溶液
答案 0 :(得分:2)
尝试使用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;
}
答案 1 :(得分: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;
}
}