Printing Excel using Interop

In order to print, you can make use of the Worksheet.PrintOut() method. You can omit any or all of the optional arguments by passing in Type.Missing. If you omit all of them, it will default to printing out one copy from your active printer. But you can make use of the arguments to set the number of copies to print, collation, etc. See help on the Worksheet.PrintOut() method for more.

The example they show in the help file is:

private void PrintToFile()
{
    // Make sure the worksheet has some data before printing.
    this.Range["A1", missing].Value2 = "123";
    this.PrintOut(1, 2, 1, false, missing, true, false, missing);
}

But unless you need to change the default settings, you can simply pass in Type.Missing for all the arguments. Here’s an example using automation to open an Excel Workbook, print the first page, and then shut down:

void PrintMyExcelFile()
{
    Excel.Application excelApp = new Excel.Application();

    // Open the Workbook:
    Excel.Workbook wb = excelApp.Workbooks.Open(
        @"C:\My Documents\Book1.xls",
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
        Type.Missing, Type.Missing,Type.Missing,Type.Missing);

    // Get the first worksheet.
    // (Excel uses base 1 indexing, not base 0.)
    Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1];

    // Print out 1 copy to the default printer:
    ws.PrintOut(
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
        Type.Missing, Type.Missing, Type.Missing, Type.Missing);

    // Cleanup:
    GC.Collect();
    GC.WaitForPendingFinalizers();

    Marshal.FinalReleaseComObject(ws);

    wb.Close(false, Type.Missing, Type.Missing);
    Marshal.FinalReleaseComObject(wb);

    excelApp.Quit();
    Marshal.FinalReleaseComObject(excelApp);
}

Hope this helps!

Mike

Leave a Comment