有没有人知道如何使用C#和Excel Interop以编程方式打印excel文件?如果是这样,请提供代码吗?
答案 0 :(得分:25)
要进行打印,您可以使用 Worksheet.PrintOut()方法。您可以通过传递Type.Missing来省略任何或所有可选参数。如果省略所有这些,则默认从活动打印机打印出一份副本。但您可以使用参数来设置要打印的副本数量,整理等。有关更多信息,请参阅 Worksheet.PrintOut()方法的帮助。
他们在帮助文件中显示的示例是:
private void PrintToFile()
{
// Make sure the worksheet has some data before printing.
this.Range["A1", missing].Value2 = "123";
this.PrintOut(1, 2, 1, false, missing, true, false, missing);
}
但除非您需要更改默认设置,否则只需传递Type.Missing所有参数即可。这是一个使用自动化打开Excel工作簿,打印第一页,然后关闭的示例:
void PrintMyExcelFile()
{
Excel.Application excelApp = new Excel.Application();
// Open the Workbook:
Excel.Workbook wb = excelApp.Workbooks.Open(
@"C:\My Documents\Book1.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.)
Excel.Worksheet ws = (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);
}
希望这有帮助!
麦克
答案 1 :(得分:2)
重要的改进是选择打印机的代码,例如:
var printers = System.Drawing.Printing.PrinterSettings.InstalledPrinters;
int printerIndex = 0;
foreach(String s in printers)
{
if (s.Equals("Name of Printer"))
{
break;
}
printerIndex++;
}
xlWorkBook.PrintOut(Type.Missing, Type.Missing, Type.Missing, Type.Missing,printers[printerIndex], Type.Missing, Type.Missing, Type.Missing);
答案 2 :(得分:0)
已经给出的所有答案都是好的,但我只是想通过显示对话框和定义打印页面方向的更多选项使它保持简单得多。
private void PrintExcel()
{
string filePath = "C:\file\location\here\";
Excel.Application excelApp = new Excel.Application();
// Open Workbook:
Excel.Workbook wb = excelApp.Workbooks.Open(filePath);
// Define the orientation for the page
((Excel._Worksheet)wb.ActiveSheet).PageSetup.Orientation = Excel.XlPageOrientation.xlLandscape;
//Decide which worksheet to print
Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1];
// Option to print with or to show dialogue box
bool userDidntCancel = excelApp.Dialogs[Excel.XlBuiltInDialog.xlDialogPrint].Show();
// Option to print out wihtout the dialogue box.
// WARNING: Do not use Dialogue option and this at the same time.
// It will print the page even if you cancel the dialogue print option.
ws.PrintOut();
// Cleanup your code
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.FinalReleaseComObject(ws);
wb.Close(false, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(wb);
// Close/Exit File
excelApp.Quit();
Marshal.FinalReleaseComObject(excelApp);
}
我希望这对别人有所帮助。 :D