Home » excel » c# – Excel PrintPreview

c# – Excel PrintPreview

Posted by: admin May 14, 2020 Leave a comment

Questions:

The Following is my code to print preview for an excel document.

The compilation is successful.

But the preview window is not visible. Can any body point me what is the error. Is there is need to add any more codings or dlls.

(Note: The Document contains data)

        Excel.Application excelApp = new Excel.Application();

        Excel.Workbook wb = excelApp.Workbooks.Open(@"C:\Documents and Settings\Admin\Desktop\DoCoMo\news5.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);
        Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1];
        bool userDidntCancel = 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);




        GC.Collect();
        GC.WaitForPendingFinalizers();
        wb.Close(false, Type.Missing, Type.Missing);
        excelApp.Quit();
How to&Answers:

You might have to manually show the Excel window:

excelApp.Visible = true;

However, I’ve heard that they are some issues related to specific Excel versions (it might work for some, and not for others).

Answer:

You need to set the Visible property of the excelApp to true.

Excel.Application excelApp = new Excel.Application();
excelApp.Visible = true;