简体   繁体   中英

How can I convert excel file to pdf using C# winforms?

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 ");

Instead of saving with the SaveAs method, use the ExportAsFixedFormat method on the workbook for exporting to PDF format:

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

Also, I would recommend against over-utilizing the object data type, which is a rather broad type. For instance, object outputFileName should be string outputFileName . It is easier for both the compiler and for other people reviewing your code if more specific data types are being used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM