方试一:使用Aspose.Cells组件(可以使用破解版),不需要按装Office,直接调用默认打印机打印,不会显示打印预览。
Workbook workbook = new Workbook("C:/abc.xlsx");
//Get the worksheet to be printed
Worksheet worksheet = workbook.Worksheets[0];
//PageSetup pageSetup = worksheet.PageSetup;
//pageSetup.Orientation = PageOrientationType.Landscape;
//pageSetup.LeftMargin = 0;
//pageSetup.RightMargin = 0.1;
//pageSetup.BottomMargin = 0.3;
//pageSetup.PrintArea = "A2:J29";
//Apply different Image / Print options.
Aspose.Cells.Rendering.ImageOrPrintOptions options = new Aspose.Cells.Rendering.ImageOrPrintOptions();
//Set the Printing page property
//options.PrintingPage = PrintingPageType.IgnoreStyle;
//Render the worksheet
SheetRender sr = new SheetRender(worksheet, options);
System.Drawing.Printing.PrinterSettings printSettings = new System.Drawing.Printing.PrinterSettings();
string strPrinterName = printSettings.PrinterName;
//send to printer
//System.Drawing.Image map = sr.ToImage(0);
sr.ToPrinter(strPrinterName);
方式二:使用Microsoft.Office.Interop.Excel(可在Nuget中按装),可显示打印预览界面,但需要按装Office。
void Print()
{
Excel.Application excelApp = new Excel.Application();
//不可或缺
excelApp.Visible = true;
Excel.Workbook wb = excelApp.Workbooks.Open("C:/abc.xlsx", Type.Missing, Type.Missing,
Type.Missing, Type.Missing,
Type.Missing, Type.Missing,
Type.Missing, Type.Missing,
Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1];
try
{
bool userDidntCancel = excelApp.Dialogs[Excel.XlBuiltInDialog.xlDialogPrintPreview].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);
}
catch (Exception en)
{
}
GC.Collect();
GC.WaitForPendingFinalizers();
wb.Close(false, Type.Missing, Type.Missing);
excelApp.Quit();
}
方式三:需要按装Office,启动Excel进程直接打印文件,但会显示Excel程序。
void Print()
{
System.Diagnostics.Process process = new System.Diagnostics.Process(); //系统进程
process.StartInfo.CreateNoWindow = true; //不显示调用程序窗口
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;//
process.StartInfo.UseShellExecute = true; //采用操作系统自动识别模式
process.StartInfo.FileName = "D:/abc.xlsx"; //要打印的文件路径
process.StartInfo.Verb = "Print"; //指定执行的动作,打印:print 打开:open …………
process.Start(); //开始打印
}
方式四:使用dsoframerocx控件