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

问题描述 投票:0回答:1

我有以下代码:[谢谢迈克·罗森布鲁姆!]

using System;
using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;

namespace ConsoleApplication17
{
    class 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 互操作性。有人有什么想法吗?

提前致谢。

c# interop printing
1个回答
8
投票

打印对话框可从 .NET 访问,并且可以在使用 12.0 PIA 的 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) 键,因此没有发生任何操作。

希望这能让你继续前进......

© www.soinside.com 2019 - 2024. All rights reserved.