Home » excel » excel – How to convert single sheet in XLS to PDF using VB.NET

excel – How to convert single sheet in XLS to PDF using VB.NET

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have working code that will convert an xls to pdf, however, the code converts the whole workbook and I really just need to select a single sheet out of the workbook, but I can’t figure out how to do it.

The code I currently use is:

Dim fileName As String = "filepath\filename"
Dim xlsApp = New Microsoft.Office.Interop.Excel.Application
xlsApp.ScreenUpdating = False
Dim xlsBook As Microsoft.Office.Interop.Excel.Workbook
Dim paramExportFormat As XlFixedFormatType = XlFixedFormatType.xlTypePDF
Dim paramExportQuality As XlFixedFormatQuality = XlFixedFormatQuality.xlQualityStandard
Dim paramOpenAfterPublish As Boolean = False
Dim paramIncludeDocProps As Boolean = True
Dim paramIgnorePrintAreas As Boolean = True
Dim paramFromPage As Object = Type.Missing
Dim paramToPage As Object = Type.Missing
xlsBook = xlsApp.Workbooks.Open(fileName & ".xls", UpdateLinks:=False, ReadOnly:=False)
xlsBook.ExportAsFixedFormat(paramExportFormat, fileName & ".pdf", paramExportQuality, paramIncludeDocProps, paramIgnorePrintAreas, paramFromPage, paramToPage, paramOpenAfterPublish)
xlsBook.Close(SaveChanges:=False)
xlsApp.Quit()

Where in the code do I need to specify the sheet in the workbook? Note that I will need to make it so that depending on an option fed into the app, the sheet will change, though I don’t think that should make a difference, but I thought I’d mention it either way.

How to&Answers:

Try to use ExportAsFixedFormat method

Private Sub SaveWorksheetAsPDF()
    Dim mySheet As Microsoft.Office.Tools.Excel.Worksheet = xlsBook(0)

    mySheet.ExportAsFixedFormat( _
        Excel.XlFixedFormatType.xlTypePDF, _
        "c:\myWorksheet", _
        Excel.XlFixedFormatQuality.xlQualityStandard, _
        True, _
        True, _
        1, _
        10, _
        False)
End Sub