Вопрос

I am trying to print an excel (2003) sheet programatically using c#. There's probably some reference I need to add but after doing some searching, even with a couple suggested references I can't figure out what code to use either because everything I have tried doesn't work for some reason, so I don't even have any example code to post to show what I have so far. I basically have no idea how to make my program print a selected excel sheet so any help would be great.

Thanks in advance.

Это было полезно?

Решение

So basically the best way I figured out to do this is using 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 brings about the print dialogue box and will return either true or false indicating whether the user pressed "PRINT" or "CANCEL" in the print dialog box which you can either use or not. I preferred this method because it allows the user to change printers and other properties and in my opinion is much better this way.

The only problem I found with this is that it prints which ever worksheet was last manually opened and saved. For example, in my case, my program is making some changes to a worksheet and then saving it. However, if the user manually opened the worksheet outside of the program and saved something on a different worksheet, my program will print that worksheet instead of the one it just edited. I can't seem to figure out how to fix this so if anyone has any suggestions, feel free to comment.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top