C# Excel interop: Exception from HRESULT (DISP_E_BADINDEX)

泪湿孤枕 提交于 2019-11-30 21:15:18

I spoke too soon! This is just a really dumb error. I thought I'd give the solution so others might not fall into the same trap as I did ;-)

To analyse the problem further, I added following code to the constructor:

List<XLS.Worksheet> sheets = new List<XLS.Worksheet>()
foreach(XLS.Worksheet sh in _WSs)
{
    sheets.Add(sh);
}
if(_OnXLSEvent != null) _OnXLSEvent(String.Format("\n\tSheets in WB: {0}\n\tFirst Sheet index: {1}, \n\tLast Sheet index: {2}",
                                                  _WSs.Count,
                                                  sheets[0].Index,
                                                  sheets.Last().Index));

This resulted in following log on my machine:

Sheets in WB: 3
First Sheet index: 1, 
Last Sheet index: 3

But in following log on the target machine:

Sheets in WB: 1
First Sheet index: 1, 
Last Sheet index: 1

Conclusion: the amount of worksheets that are standard added to a new workbook differ from user to user. Something to keep in mind!

You can check if worksheets are not present then add them. Usually first worksheet is created by default and you can check rest as below. I had similar issue and resolved as below.

           // Add Worksheet 2 if not present
            if (workbook.Worksheets.Count < 2)
            {
                workbook.Worksheets.Add();
            }

            // Add Worksheet 3 if not present
            if (workbook.Worksheets.Count < 3)
            {
                workbook.Worksheets.Add();
            }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!