Excel to pdf using interop

outlook email picture outlook email · May 10, 2017 · Viewed 7.5k times · Source

I am converting excel file to pdf using interop. and i have a working code.

but before saving it to pdf. it prompt a dialog box which ask the user to "save changes to the file or not" how can i avoid this prompt?

and how can i close the excel when saving is done? Thank you

public string ExceltoPdf(string excelLocation, string outputLocation)
        {
            try
            {
                Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
                app.Visible = false;
                Microsoft.Office.Interop.Excel.Workbook wkb = app.Workbooks.Open(excelLocation);
                wkb.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, outputLocation);

                wkb.Close();
                app.Quit();

                return outputLocation;

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
                throw ex;
            }
        }

Answer

NetMage picture NetMage · May 10, 2017

Try adding

app.DisplayAlerts = False

after you set .Visible.