簡體   English   中英

如何使用 C# winforms 將 excel 文件轉換為 pdf?

[英]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 ");

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

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

此外,我建議不要過度使用對象數據類型,這是一種相當廣泛的類型。 例如, object outputFileName應該是string outputFileName 如果使用了更具體的數據類型,則編譯器和其他人都可以更輕松地查看您的代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM