使用c#打印Excel 2003工作表

时间:2013-09-06 20:09:28

标签: c# printing excel-2003

我正在尝试使用c#以编程方式打印excel(2003)表。可能有一些参考我需要添加,但经过一些搜索后,即使有一些建议的参考,我也无法弄清楚要使用的代码,因为我尝试过的所有内容都因某些原因无效,所以我甚至都没有有任何示例代码发布,以显示我到目前为止。我基本上不知道如何让我的程序打印选定的Excel表格,所以任何帮助都会很棒。

提前致谢。

1 个答案:

答案 0 :(得分:1)

所以基本上我想出的最好方法是使用Microsoft.Office.Interop.Excel

object misValue = System.Reflection.Missing.Value;

Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wb = excelApp.Workbooks.Open(Form1.excelPath, misValue, misValue, misValue, 
    misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[1];

//bring about print dialogue
bool userDidntCancel = excelApp.Dialogs[Microsoft.Office.Interop.Excel.XlBuiltInDialog.xlDialogPrint].Show(misValue,
    misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue,
    misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue,
    misValue, misValue, misValue, misValue, misValue);

userDidntCancel带来打印对话框,将返回true或false,指示用户是否在打印对话框中按“PRINT”或“CANCEL”,您可以使用或不使用。我更喜欢这种方法,因为它允许用户更改打印机和其他属性,在我看来这种方式要好得多。

我发现的唯一问题是它打印了上次手动打开和保存的工作表。例如,在我的情况下,我的程序正在对工作表进行一些更改,然后保存它。但是,如果用户在程序外部手动打开工作表并在不同的工作表上保存了某些内容,我的程序将打印该工作表而不是刚刚编辑的工作表。我似乎无法弄清楚如何解决这个问题,所以如果有人有任何建议,请随时发表评论。