1

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

提前致谢。

4

1 回答 1

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”,您可以使用或不使用。我更喜欢这种方法,因为它允许用户更改打印机和其他属性,而且我认为这种方法要好得多。

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

于 2013-10-04T21:56:29.507 回答