TrevorBrooks TrevorBrooks - 1 month ago 30
C# Question

Microsoft.Office.Interop.Excel PrintOut Throws Error

I'm using Microsoft.Office.Interop.Excel in a .Net Framework 4.5 Windows Service project on my 64bit Windows 7 desktop workstation and everything appears to be working except the PageSetup properties and more importantly the PrintOut method of the Worksheet object.

Here's the code:

Microsoft.Office.Interop.Excel.Application ExcelApp = null;
Microsoft.Office.Interop.Excel.Workbook WBook = new Microsoft.Office.Interop.Excel.Workbook;
Microsoft.Office.Interop.Excel.Worksheet WSheet = new Microsoft.Office.Interop.Excel.Worksheet);

ExcelApp = new Microsoft.Office.Interop.Excel.Application();

WBook = ExcelApp.Workbooks.Add();

WSheet = WBook.Worksheets[1];

//Do some stuff with the sheet

//None of this works, throws an error: Unable to set the Orientation property of the PageSetup class
WSheet.PageSetup.Orientation = Microsoft.Office.Interop.Excel.XlPageOrientation.xlLandscape;
WSheet.PageSetup.Zoom = false;
WSheet.PageSetup.FitToPagesWide = 1;
WSheet.PageSetup.FitToPagesTall = false;

//Throws Error (see below)
WSheet.PrintOut(null, null, null, null, null, null, null);


PrintOut() Error: No printers are installed. To install a printer click the File tab, and then click Print. Click No Printers Installed, and then click Add Printer. Follow the instructions in the Add Printer dialog box.

I definitely have printers defined in my Devices and Printers. I have a network printer set as my Default. I have even added this printer to Win.ini as I've seen this recommended in other posts but to no avail.

Answer

I figured this out while writing up the question.

Make sure you are running your Windows Service under an account that has printers set up and a specified Default printer. I was running the service under Local Service account, once I switched it to run under my personal account both the PageSetup properties and the PrintOut() method worked!