0

I'm trying to find a way to have the excel file automatically open as soon as it is done downloading. The file is called "ExportAging.xlsx" and the closest I've gotten to the solution is this:

enter image description here

This is the code I have

  private void ExportToExcel()
    {
      try
       {
          SaveFileDialog saveDialog = new SaveFileDialog();
          saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx";
          saveDialog.FilterIndex = 1;
          saveDialog.FileName = "ExportAging";
            if (saveDialog.ShowDialog() == DialogResult.OK)
            {
               workbook.SaveAs(saveDialog.FileName);
               saveDialog.OpenFile();
            }
        }
      catch (System.Exception ex)
        {
          MessageBox.Show(ex.Message);
        }
      finally
        {
          excel.Quit();
          workbook = null;
          excel = null;
        }
   }

Any help is appreciated.

  • Im not an expert but maybe one of the classes you are using implements IDisposable, this means you should call Dispose() afterwards. otherwise i dont think its this program (b)locking the file. – Joel Harkes Oct 19 '16 at 19:45
  • I'd guess you need your `workbook` object to release the file before you open it with the `saveDialog` object. – Michael Armes Oct 19 '16 at 19:46
  • I think Meghan is onto something. Make sure that your workbook.SaveAs method disposes any FileStream that it uses. – Dave Smash Oct 19 '16 at 19:48
  • 1
    Just replace excel.Quit(); with excel.Visible = true; – Slai Oct 19 '16 at 19:48
  • @Slai Please post your comment as an answer so I can give you credit. It worked like a charm. –  Oct 19 '16 at 19:50
  • BTW excel.Quit(); usually does not close the Excel instance if not disposed properly – Slai Oct 19 '16 at 19:51

1 Answers1

0

So, no need to close the Excel Application and then reopen it:

if (saveDialog.ShowDialog() == DialogResult.OK)
{
   workbook.SaveAs(saveDialog.FileName);
   excel.Visible = true;
}

Another option can be to close the file after saving it:

if (saveDialog.ShowDialog() == DialogResult.OK)
{
   workbook.SaveAs(saveDialog.FileName);
   workbook.Close(false);
}

Disposing of Microsoft.Office.Interop.Word.Application

Community
  • 1
  • 1
Slai
  • 22,144
  • 5
  • 45
  • 53