Does anybody have any idea how to print an excel file programatically using C# and the Excel Interop? If so, can you please provide code?
using (ExcelPackage xlPackage = new ExcelPackage(existingFile)) { // get the first worksheet in the workbook ExcelWorksheet worksheet = xlPackage. Workbook. Worksheets[1]; int iCol = 2; // the column to read // output the data in column 2 for (int iRow = 1; iRow < 6; iRow++) Console. WriteLine("Cell({0},{1}).
First, Remove 'Microsoft. Office. Interop. Excel' nuget package, and then add reference to 'Microsoft Excel 16.0 Object Library' (right click the project -> 'Add' -> 'Reference' -> search and add 'Microsoft Excel 16.0 Object Library' ).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With