title: Exporting Excel file to PDF - getting stuck trying to close Excel file
body: <p>I have a function that takes a url to an Excel file, and then exports it as a pdf:</p>
  
  <pre><code>public static void ExportFromExcel(string url)
  {
      // Create COM Objects
      Application excelApplication = new Application();
      Workbook excelWorkbook = 
          excelApplication.Workbooks.Open(HttpContext.Current.Server.MapPath(url));
  
      try
      {
          // Call Excel's native export function
          excelWorkbook.ExportAsFixedFormat(
              XlFixedFormatType.xlTypePDF, 
              HttpContext.Current.Server.MapPath(url.Replace(".xlsx", ".pdf")));
      }
      catch (Exception ex)
      {
  
      }
      finally
      {
          // Close the workbook, quit Excel, and clean up regardless of the results
          excelWorkbook.Close();    // HANGS AND FAILS HERE
          excelApplication.Quit();
  
          excelApplication = null;
          excelWorkbook = null;
      }
  }
  </code></pre>
  
  <p>What I'm doing is creating an Excel file, and then immediately creating a pdf from that file:</p>
  
  <pre><code>using (FileStream fs = File.Create(HttpContext.Current.Server.MapPath(filePath)))
  {
      byte[] data = pck.GetAsByteArray();
      fs.Write(data, 0, data.Length);
  }
  
  Pdf.ExportFromExcel(filePath);
  </code></pre>
  
  <p>It will create the Excel file just fine, and it will also create the pdf. But the page hangs for a long time, and then gives me the error at <code>excelWorkbook.Close();</code> in my pdf code:</p>
  
  <blockquote>
    <p><strong>The remote procedure call failed. (Exception from HRESULT: 0x800706BE)</strong></p>
  </blockquote>
  
  <p>The files actually get created though. But if I go to the file directory, there is a temporary Excel file as well (my Excel filename with the <code>~$</code> in front of it).</p>
  
  <p>If I try and delete my Excel file, I get an error saying the file is being used by another process, and I can't delete my Excel file until I kill the EXCEL.EXE in the Task Manager.</p>
  
  <p>So for some reason, my Excel file won't close after it finishes creating the pdf. Am I doing something wrong in my code?</p>