My Blog

Printing Excel Sheet/Workbook

In continuation from here

To print an Excel Sheet use this code.

Imports Excel = Microsoft.Office.Interop.Excel

Public Class Form1
    '~~> Define your Excel Objects
    Dim xlApp As New Excel.Application
    Dim xlWorkBook As Excel.Workbook
    Dim xlWorkSheet As Excel.Worksheet

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        '~~> Opens Source Workbook. Change path and filename as applicable
        xlWorkBook = xlApp.Workbooks.Open("C:\Tutorial\Sample.xlsx")

        '~~> Display Excel
        xlApp.Visible = True

        '~~> Set the source worksheet
        xlWorkSheet = xlWorkBook.Sheets("Sheet1")

        '~~> Printing the Excel Sheet
        xlWorkSheet.PrintOut(From:=1, To:=1, Copies:=1, Collate:=True)
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        Me.Close()
    End Sub
End Class

However when you want to print the complete Excel File then here are two ways you can do it.

If you want to simply print the file without checking the file then you can use this.

Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
    Dim oProcess As New System.Diagnostics.Process
    With oProcess.StartInfo
        .CreateNoWindow = True
        .WindowStyle = ProcessWindowStyle.Hidden
        .Verb = "print"
        .UseShellExecute = True
        .FileName = "C:\Tutorial\Sample.xlsx"
    End With
    oProcess.Start()
End Sub

And if you want to print the file from Excel then use this.

Imports Excel = Microsoft.Office.Interop.Excel

Public Class Form1
    '~~> Define your Excel Objects
    Dim xlApp As New Excel.Application
    Dim xlWorkBook As Excel.Workbook
    Dim xlWorkSheet As Excel.Worksheet

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        '~~> Opens Source Workbook. Change path and filename as applicable
        xlWorkBook = xlApp.Workbooks.Open("C:\Tutorial\Sample.xlsx")

        '~~> Display Excel
        xlApp.Visible = True

        '~~> Printing the Excel Workbook
        xlWorkBook.PrintOut(From:=1, To:=1, Copies:=1, Collate:=True)

        '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        ' If you just want to print a particular range, say A1:B10 then use the below
        '
        ' xlWorkSheet = xlWorkBook.Sheets("Sheet1")
        ' xlWorkSheet.Range("A1", "E1").PrintOut(From:=1, To:=1, Copies:=1, Collate:=True)
        '
        '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        Me.Close()
    End Sub
End Class