Home » excel » c# – Cannot convert 'System.__ComObject' to 'System.Web.UI.WebControls.ListItem

c# – Cannot convert 'System.__ComObject' to 'System.Web.UI.WebControls.ListItem

Posted by: admin May 14, 2020 Leave a comment

Questions:

The code below gives me the error: cannot convert COM object of type 'System.__ComObject' to class type 'System.Web.UI.WebControls.ListItem.

Excel.Application app = new Excel.Application();
Excel.Workbook workbk;

workbk = app.Workbooks.Open(savePath);
//ArrayList a = new ArrayList();
foreach (var list in workbk.Sheets)
{
    ListBox1.Items.Add((ListItem)list);
}

Why am I receiving the error?

How to&Answers:

As the error implies, the worksheet from the Sheets collection is not a ListItem. You need to do some sort of conversion in between (for example, grabbing the cell values, or the sheet name, or something else)