使用互操作将 Excel 转为 pdf

out*_*ail 6 c# pdf excel excel-interop

我正在使用互操作将 excel 文件转换为 pdf。我有一个工作代码。

但在将其保存为 pdf 之前。它会提示一个对话框,要求用户“是否保存对文件的更改”,我该如何避免此提示?

保存完成后如何关闭excel?谢谢

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;
            }
        }
Run Code Online (Sandbox Code Playgroud)

Net*_*age 3

尝试添加

app.DisplayAlerts = False
Run Code Online (Sandbox Code Playgroud)

设置后.Visible