title: System.Runtime.InteropServices error when exporting dataGridView to Excel workbook
body: <p>I have an application that displays certain database data, and includes a function to save that data to an excel workbook on request using the Microsoft.Office.Interop.Excel assembly. One of my users reports the following error when trying to save to an excel workbook:</p>
  
  <p>System.Runtime.InteropServices.COMException (0x8002000B): Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))
     at Microsoft.Office.Interop.Excel.Sheets.get__Default(Object Index)
     at WorkCalendar.Form1.saveBtn_Click(Object sender, EventArgs e)</p>
  
  <p>We've verified that he does have Excel 2013 installed and all of the necessary assemblies came through ok according to the full exception details, so I hope one of you can shed some light on what's going on here.</p>
  
  <p>Here's the saveBtn_Click event method mentioned in the error above (edited for conciseness)</p>
  
  <pre><code>    private void saveBtn_Click(object sender, EventArgs e)
      {
          // creating Excel Application
          _Application app = new Microsoft.Office.Interop.Excel.Application();
          _Workbook workbook;
          _Worksheet worksheet;
  
          string fetchString = fetch.ToString("HH.mm.ss");
  
          try 
          {
              // Check for existing workbook and add new page
          }
          catch
          {
              // If no workbook found, create a brand new one
              workbook = app.Workbooks.Add(Type.Missing);
              worksheet = null;
              worksheet = workbook.Sheets["Sheet1"];
          }
  
          try
          {
              // do not show the excel sheet being created
              app.Visible = false;
  
              worksheet = workbook.ActiveSheet;
              worksheet.Name = fetchString;
  
              // Get dataGridView data, insert it into the excel worksheet and format it
          }
          catch { }
          finally
          {
              // save the application
  
              // Exit from the application
              app.Quit();
          }
      }
  </code></pre>
  
  <p>As I said, the application works fine on my and other computers on which it's been tested. Any ideas?</p>
  
  <p>EDIT: Altered code example slightly to show the method looking for an existing workbook, and creating one if no workbook found.</p>