使用Excel Interop并获取打印对话框

3
我有以下代码:[感谢 Mike Rosenblum!]
使用 System; 使用 System.Collections.Generic; 使用 System.Linq; 使用 System.Text; 使用 Microsoft.Office.Interop.Excel; 使用 System.Runtime.InteropServices;
命名空间 ConsoleApplication17 { 类 Program {
    static void Main(string[] args) {



    //public void PrintMyExcelFile() 
    //{
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();

// Open the Workbook:
Microsoft.Office.Interop.Excel.Workbook wb = excelApp.Workbooks.Open(
    @"C:\hello.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.)
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.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);



}
    }




    }

我想实现的是,不直接打印我的Excel文件,而是弹出一个打印对话框,以便我可以选择特定的打印机。
我正在使用Excel的12.0.0.0 .NET互操作性。 有人有什么想法吗?
提前致谢。
1个回答

8

打印对话框可从.NET访问,并且使用12.0 PIAs可以在Excel 2007上正常运行。但是,Dialog.Show()命令有30个可选参数。在将来的C# 4.0中,可以省略可选参数(谢天谢地),而VB.NET则不需要它们,但如果使用C# 3.0或更低版本,则必须为可选参数提供Type.Missing。所有30个参数:

bool userDidntCancel =
    excelApp.Dialogs[Excel.XlBuiltInDialog.xlDialogPrint].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);

Show()方法返回'true'表示操作成功;返回'false'表示用户按下了取消按钮或者按下了ESC键,因此没有进行任何操作。

希望这能给你带来帮助...


再次感谢你作为救命稻草的帮助!非常感激你的帮助。 - yeahumok
我已经浏览了上面的代码。我也遇到了类似的问题,即打印预览选项。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]; - M.Thillai
尝试了解决方案后,打印机对话框没有弹出。我的网站一直挂起。您知道可能纠正它的方法吗?谢谢! - user613334
@john - 网站卡住了?我不会从服务器端代码尝试这个。这意味着打印对话框可能会在服务器上显示,是的,它会卡住。 - Johan Danforth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接