Code to Convert Excel to PDF using VB.NET

2019-08-30 10:22发布

问题:

I have VB code to convert .xlsx to .pdf in SCRIPT TASK. When I run the task its running successfully without any erros. But the Excel file is not converting to pdf format.

I have added Microsoft.Office.Interop.Excel reference to the task. Please look into the below code. I could not know what is the error in this.

Please help. Thanks in advance.

Imports Excel = Microsoft.Office.Interop.Excel
Imports System.IO
Imports System.Data.SqlClient
Imports System.Text
Imports Microsoft.Office.Interop.Excel
Imports Microsoft.SqlServer.Dts.Runtime


<System.AddIn.AddIn("ScriptMain", Version:="1.0", Publisher:="", Description:="")> _
<System.CLSCompliantAttribute(False)> _
Partial Public Class ScriptMain
Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase

Enum ScriptResults
    Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
    Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
End Enum

Public Sub Main()

    Dim oApplication As ApplicationClass = New ApplicationClass()
    Dim oWorkbook As Workbook = Nothing
    Dim PDFFile As String = "D:\Convert XL to PDF\Test.pdf"
    Dim pFormatType As XlFixedFormatType = XlFixedFormatType.xlTypePDF
    Dim pQuality As XlFixedFormatQuality = XlFixedFormatQuality.xlQualityMinimum
    Dim pIncludeDocProperties As Boolean = True
    Dim pIgnorePrintAreas As Boolean = True
    Dim pFrom As Object = Type.Missing
    Dim pTo As Object = Type.Missing
    Dim pOpenAfterPublish As Boolean = False

    Try
        oWorkbook = oApplication.Workbooks.Open("D:\Convert XL to PDF\convert.xlsx")
        Dim oWorksheet As Excel.Worksheet
        oWorksheet = oApplication.Worksheets(1)
        oWorksheet.PageSetup.FitToPagesWide = 1
        oWorksheet.PageSetup.FitToPagesTall = 1
        oWorksheet.PageSetup.Zoom = False
        If Not oWorkbook Is Nothing Then
            oWorkbook.ExportAsFixedFormat(pFormatType, PDFFile, pQuality, _
                                          pIncludeDocProperties, _
                                          pIgnorePrintAreas, _
                                          pFrom, pTo, pOpenAfterPublish)
        End If
    Catch ex As Exception

    End Try

    If Not oWorkbook Is Nothing Then
        oWorkbook.Close(False)
        oWorkbook = Nothing
    End If

    If Not oApplication Is Nothing Then
        oApplication.Quit()
        oApplication = Nothing
    End If

    GC.Collect()
    GC.WaitForPendingFinalizers()

    Dts.TaskResult = ScriptResults.Success
End Sub
End Class