将Excel电子表格保存为PDF

我正在尝试使用Visual Basic将Excel电子表格保存为PDF文件。 我在网上find了一些示例代码(见下面),但是我打开了一个Visual Basic似乎不能识别的Workbook对象。 build议…

' 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" 

迟到版本的nutch的答案..

 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我build议开发与Office PIA的(所以你得到智能感知和帮助),然后在发布之前,切换到迟绑定,所以你没有被locking到一个特定版本的Office(也,所以你不需要分发PIA与您的应用程序)

这只是如何从Excel中创buildPDF的方法之一 – 您可以通过程序访问任何程序(以扩大您的体验)。 这是通过使用虚拟打印机。 你会需要

  • 下载虚拟PDF打印机(许多可用,有些是免费的)。 此外,了解什么types的PDF任何给定的打印机创build – 光栅PDFvectorPDF格式 。 光栅创build更大的文件。
  • 安装它(虚拟打印机)
  • 在代码中 – 你通常设置打印机属性,然后
  • 你在代码中使用interop打开excel并调用Print ,在其中设置打印机 – 虚拟PDF打印机,并根据打印机设置选项“打印到文件”。 某些虚拟打印机不需要,因为您预设了它们的属性甚至(某些打印机)registry项,在其中设置文件名。

代码示例通常来自打印机供应商。 还有更多不同的相关博客。 Google“.net的虚拟打印机”

而我认为,如果你使用旧的interop / excel(对不起,我真的不能告诉版本中断) – 这是唯一的方法来做到这一点。

工作簿不是Excel Interop的一类,也不是一类系统。 此示例代码基于Spire.XLS ,这是一个允许用户在.NET中操作Excel文件的第三方组件。 在运行程序之前,您需要下载并将DLL引用到您的项目中。