首页 > 解决方案 > 如何使用 C# winforms 将 excel 文件转换为 pdf?

问题描述

Microsoft.Office.Interop.Excel.Application execl =
    new Microsoft.Office.Interop.Excel.Application();
       
        object oMissing = System.Reflection.Missing.Value;
        FileInfo execlFile = new FileInfo(txtNameFile.Text);
        execl.Visible = false;
        execl.ScreenUpdating = false;
        object filename = (object)execlFile.FullName;
        Workbook doc = execl.Workbooks.Open(ref filename, ref oMissing
            , ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing
            , ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing
            , ref oMissing, ref oMissing, ref oMissing, ref oMissing);
        doc.Activate();
        object outputFileName = execlFile.FullName.Replace(".Xls", ".pdf");
        object fileformat = WdSaveFormat.wdFormatPDF;
        doc.SaveAs2(ref outputFileName,
           ref fileformat, ref oMissing, ref oMissing
           , ref oMissing, ref oMissing, ref oMissing, ref oMissing
           , ref oMissing, ref oMissing, ref oMissing, ref oMissing
           , ref oMissing, ref oMissing, ref oMissing, ref oMissing);
        object savechanges = WdSaveOptions.wdSaveChanges;
        ((Workbooks)doc).Close(ref savechanges, ref oMissing, ref oMissing);
        doc = null;
        ((_Application)execl).Quit(ref oMissing, ref oMissing, ref oMissing);
        execl = null;
        MessageBox.Show("The File has been converted to PDF ");

标签: c#winformsxlsx

解决方案


不要使用 SaveAs 方法保存,而是使用工作簿上的 ExportAsFixedFormat 方法导出为 PDF 格式:

doc.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, outputFileName);

另外,我建议不要过度使用对象数据类型,这是一种相当广泛的类型。例如,object outputFileName应该是string outputFileName。如果使用更具体的数据类型,编译器和其他人检查您的代码会更容易。


推荐阅读