簡體   English   中英

將 Excel 電子表格另存為 PDF

[英]Save Excel spreadsheet as PDF

我正在嘗試使用 Visual Basic 將 Excel 電子表格保存為 PDF 文件。 我在網上找到了一些示例代碼(見下文),但它讓我打開了一個 Visual Basic 似乎不再識別的 Workbook 對象。 建議...

                       ' load Excel file
        Dim workbook As New Workbook()
        workbook.LoadFromFile("D:\test.xlsx")

        ' Set PDF template
        Dim pdfDocument As New PdfDocument()
        pdfDocument.PageSettings.Orientation = PdfPageOrientation.Landscape
        pdfDocument.PageSettings.Width = 970
        pdfDocument.PageSettings.Height = 850

        'Convert Excel to PDF using the template above
        Dim pdfConverter As New PdfConverter(workbook)
        Dim settings As New PdfConverterSettings()
        settings.TemplateDocument = pdfDocument
        pdfDocument = pdfConverter.Convert(settings)

        ' Save and preview PDF
        pdfDocument.SaveToFile("sample.pdf")
        System.Diagnostics.Process.Start("sample.pdf")

您可以使用.ExportAsFixedFormat函數來更簡單,例如

Dim workbook As New Workbook()
workbook.LoadFromFile("D:\test.xlsx")

workbook.activesheet.ExportAsFixedFormat xlTypePDF, "D:\test.pdf"

納奇答案的后期版本..

Option Strict Off 'Required for Late Binding     

Module XL
  Sub ExcelPDF()
    Dim xl As Object
    xl = CreateObject("Excel.Application")
    Dim xwb As Object = xl.Workbooks.Open("D:\test.xlsx")
    xwb.ActiveSheet.ExportAsFixedFormat(0, "D:\sample.pdf")
    xl.Quit()
  End Sub
End Module

PS 我建議使用 Office PIA 進行開發(因此您可以獲得 Intellisense 和幫助),然后在發布之前切換到后期綁定,這樣您就不會被鎖定到特定版本的 Office(同樣,因此您不需要分發PIA 與您的應用程序)

這只是您如何從 Excel 或就此而言創建 PDF 的方法之一 - 您可以以編程方式訪問的任何程序(以擴大您的經驗)。 它是通過使用虛擬打印機。 你會需要

  • 下載虛擬 PDF 打印機(許多可用,有些是免費的)。 此外,了解任何給定打印機創建的 PDF 類型 -光柵 pdf矢量 pdf 光柵創建更大的文件。
  • 安裝它(虛擬打印機)
  • 在代碼中 - 您通常設置打印機屬性,然后
  • 您在代碼中使用互操作打開 excel 並調用Print ,在其中設置打印機 - 您的虛擬 PDF 打印機,並根據打印機設置選項“打印到文件”。 某些虛擬打印機不需要,因為您預設了它們的屬性或什至(某些打印機)注冊表項,您可以在其中設置文件名。

代碼示例通常可從打印機供應商處獲得。 還有更多不同的相關博客。 谷歌“.net 虛擬打印機”

我的想法是,如果您使用較舊的互操作/excel(對不起,我真的不能告訴版本被切斷)-這是唯一的方法。

工作簿不是 Excel Interop 類,也不是 System 類。 此示例代碼基於Spire.XLS ,這是一個 3rd 方組件,它使用戶能夠在 .NET 中操作 Excel 文件。 在運行程序之前,您需要下載 DLL 並將其引用到您的項目中。

暫無
暫無

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

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