C# Excel interop: Exception from HRESULT (DISP_E_BADINDEX)

前端 未结 2 1048
终归单人心
终归单人心 2021-01-03 05:47

I\'m trying to deploy an application that works fine on my development pc and some other workstations. However, some users receive an error that I can\'t seem to grasp.

相关标签:
2条回答
  • 2021-01-03 06:10

    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();
                }
    
    0 讨论(0)
  • 2021-01-03 06:24

    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!

    0 讨论(0)
提交回复
热议问题