通常通過指定單元格的範圍將項目綁定到Excel組合框。在特定範圍的單元格中出現的值在Excel文件中列爲ComboBox項目。另外,即使通過引用/綁定的單元格位於不同的工作表中,Essential XlsIO也會返回適當的範圍。屬性「xlComboBox.ListFillRange」包含爲填充組合框項目而引用/綁定的單元格的範圍。使用此屬性,您可以檢索範圍,然後遍歷範圍以獲取所有組合框項目。因此,我附上了代碼片段來檢索組合框項目。
private void button1_Click(object sender, EventArgs e)
{
//Instantiate the spreadsheet creation engine.
ExcelEngine excelEngine = new ExcelEngine();
//Instantiate the excel application object.
IApplication application = excelEngine.Excel;
//Open the excel file and instantiate the workbook object
IWorkbook workbook = application.Workbooks.Open(@"..\..\Data\Book1.xlsx");
//Retrieve the Excel comboBox from the worksheet
IComboBoxShape xlComboBox = workbook.Worksheets[0].ComboBoxes[0];
//user defined method to retrieve Excel ComboBox items and populate them in a Windows forms - ComboBox control
RetrieveItemsFromExcelComboBox(xlComboBox, comboBox1);
xlComboBox = workbook.Worksheets[0].ComboBoxes[1];
RetrieveItemsFromExcelComboBox(xlComboBox, comboBox2);
//Close the workbook.
workbook.Close();
//Dispose the excel engine
excelEngine.Dispose();
}
/// <summary>
/// Retrieve the items from the Excel ComboBox and populate them in Windows form - ComboBox control
/// </summary>
/// <param name="xlComboBox">Excel combobox instance (IComboBoxShape)</param>
/// <param name="comboBox">Windows Forms - Combo Box instance</param>
private void RetrieveItemsFromExcelComboBox(IComboBoxShape xlComboBox, ComboBox wfComboBox)
{
//Get the range where the ComboBox items are present in the workbook
IRange xlRange = xlComboBox.ListFillRange;
//iterate through the range of the comboBox items and add them into the Windows forms - ComboBox control
for (int rowIndex = xlRange.Row; rowIndex <= xlRange.LastRow; rowIndex++)
{
for (int colIndex = xlRange.Column; colIndex <= xlRange.LastColumn; colIndex++)
{
wfComboBox.Items.Add(xlRange[rowIndex, colIndex].DisplayText);
}
}
wfComboBox.SelectedIndex = xlComboBox.SelectedIndex - 1;
}
讓我知道它是否對您有幫助。
有兩種類型的組合框可放置在Excel工作表上 - 「窗體」版本和ActiveX窗體。你有哪種類型? – 2012-01-13 21:29:36
表格版本 – Khaldoun 2012-01-17 14:38:44