P.C P.C - 1 month ago 9
C# Question

C# Need to have my code auto open the excel file after download is complete

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.

Answer

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