Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX) for System.Runtime.InteropServices.COMException

Somdip Dey picture Somdip Dey · Mar 3, 2015 · Viewed 52.5k times · Source

I have a part of code which tries to export data (from database) to Excel. When I am trying to perform this task, it is generating this error:

System.Runtime.InteropServices.COMException occurred
Additional information: Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))

Code which is generating this error:

string ExcelFileName = RootFolder + "\\" + "Work_Sheet.xls";
File.Copy(RootFolder + "\\" + "WorksOrder_Template.xls", ExcelFileName);
Excel.Workbook xlWorkBook;
xlWorkBook = excelApp.Workbooks.Open(ExcelFileName, 0, false, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, false, true, Type.Missing);
Excel.Worksheet Page2;
Excel.Worksheet Page3;
Page2 = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item("Sheet2");
Page3 = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item("Sheet3");

The code line on :

Page3 = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item("Sheet3");

is generating the aforementioned error. Any idea how to solve this issue?

Answer

Somdip Dey picture Somdip Dey · Mar 3, 2015

"Sheet3" was missing from WorksOrder_Template.xls file and hence, when the code tried to fetch the 'Sheet3' it generated the error.