Reputation: 228
I am doing Office automation from a C# application to Excel. I am trying to bring up a print preview dialog (or a print dialog with a preview option). I also want the user to have the ability to select a different print than the default one.
I have tried
sheet1.PrintPreview();
and
sheet1.PrintOutEx(1, 1, 1, true);
but I don't see a way for the user to select a different printer.
Upvotes: 1
Views: 5995
Reputation: 15794
Yes, there is a built-in dialog for your Windows application. If you have a reference to the Excel automation Application
object, you will be able to call up pretty much any built-in dialog that is available in Excel.
2 links that you might find helpful:
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.dialogs.aspx
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.xlbuiltindialog.aspx
Example: in order to pull up the print preview dialog, you would do this:
var excelApp = new Excel.Application();
bool dialogResult =
excelApp.Dialogs[Excel.XlBuiltInDialog.xlDialogPrintPreview].Show(
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, 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, Type.Missing, Type.Missing);
Upvotes: 2
Reputation: 28059
You change the default printer of the Application object, and then print the worksheet, like so. You can get the printers installed on the computer from System.Drawing.Printing.PrinterSettings.InstalledPrinters
and then display these to the user in some sort of dialogue, and then set the ActivePrinter
of the Excel Application instance like so, and then display the Print Preview Dialogue:
using System.Drawing.Printing;
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application application = new Excel.Application();
Excel.Workbook workbook = application.Workbooks.Add();
Excel.Worksheet worksheet = workbook.Sheets[1];
var printers = PrinterSettings.InstalledPrinters;
Console.WriteLine("Select printer (type the number):");
Console.WriteLine();
for (int i = 0; i < printers.Count; i++)
{
Console.WriteLine("{0} - {1}", i, printers[i]);
}
int selection = Convert.ToInt32(Console.ReadLine());
application.ActivePrinter = printers[selection];
worksheet.PrintPreview();
Upvotes: 1