In this tutorial I will show you how to print a Excel file using a WPF app. You might also want to look at a related post.
Create and Download Excel File Using PHP
Step 1: Add a reference to Excel Interop in your Project
Add a reference to Microsoft.Office.Interop.Excel
in your project by right clicking on References, Add Reference from the Solution Explorer. Next choose Microsoft.Office.Interop.Excel
from the Extensions tab under Assemblies.
Add a using
statement at the top of the page in which you want to add the print XlS function.
using Excel= Microsoft.Office.Interop.Excel;
Step 2: Define Public Variables for Excel
Define the following variables before the class constructor.
public Excel.Application APP = null;
public Excel.Workbook WB = null;
public Excel.Worksheet WS = null;
public Excel.Range Range = null;
Step 3: Add the Method to Print Excel
The following function opens a Excel file to print it and then closes it again.
void PrintMyExcelFile()
{
this.APP = new Microsoft.Office.Interop.Excel.Application();
// Open the Workbook:
this.Open("C:\\Users\\maska\\Documents\\MyExcel.xlsx", 1);
// Get the first worksheet.
// (Excel uses base 1 indexing, not base 0.)
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);
APP.Quit();
Marshal.FinalReleaseComObject(APP);
}
That’s it. Call this method to print an existing excel file.
Recent Comments