-->

用微软的COM组件在将Excel转换成PDF时报错

2019-01-02 20:51发布

问题:

public static bool ExcelConvertToPDF(string sourcePath, string targetPath)
        {
            bool result = false;
            Microsoft.Office.Interop.Excel.XlFixedFormatType targetType = Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF;
            object missing = Type.Missing;
            Microsoft.Office.Interop.Excel.Application application = new Microsoft.Office.Interop.Excel.ApplicationClass();
            Microsoft.Office.Interop.Excel.Workbooks workBook = application.Workbooks;
            try
            {
                application.Visible = false;
                Microsoft.Office.Interop.Excel.Workbook wb= application.Workbooks.Open(sourcePath);
                string tempPath = Path.Combine(Path.GetTempPath(), Path.GetFileName(sourcePath));
                //System.IO.DirectoryInfo DirInfo = new DirectoryInfo(Path.GetTempPath());
                // DirInfo.Attributes = FileAttributes.Archive & FileAttributes.Directory;
                //System.IO.File.SetAttributes(tempPath, System.IO.FileAttributes.Archive);
                wb.SaveAs();
                wb.ExportAsFixedFormat(targetType, targetPath);
                result = true;
            }
            catch (Exception e)
            {
                SystemLogHelper.Logger.Error(e.Message, e.InnerException ?? e);
                result = false;
            }
            finally
            {
                if (workBook != null)
                {
                    //workBook.Close(true, missing, missing);
                    workBook = null;
                }
                if (application != null)
                {
                    application.Quit();
                    application = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return result;
        }

回答1:

你是老胡吗?



回答2:

推荐你使用 Spire.XLS.dll 的系列组件,比微软的好用多了



标签: