本文将通过C#程序来介绍三种常见的Excel文档打印需求及方法,即
使用默认打印机打印Excel文档
指定打印机及设置打印选项来打印Excel文档
静默打印Excel文档
使用工具:Spire.XLS for .NET
Dll文件获取及引用:
方法1:通过官网下载dll文件。下载后,解压文件,安装。完成安装后,将安装路径下Bin文件夹中的Spire.Xls.dll程序集文件添加引用至程序。
方法2:可通过Nuget网站下载。
C#代码示例
【示例1】使用默认打印机打印
直接调用workbook.PrintDocument.Print()方法完成打印
Workbook workbook = new Workbook(); workbook.LoadFromFile("Sample.xlsx"); workbook.PrintDocument.Print();
【示例2】指定打印机,并设置打印选项
//加载Excel文档 Workbook workbook = new Workbook(); workbook.LoadFromFile("Sample.xlsx"); //获取第一个Excel工作表 Worksheet sheet = workbook.Worksheets[0]; //设置打印纸张大小 sheet.PageSetup.PaperSize = PaperSizeType.PaperA4; //设置打印方向 sheet.PageSetup.Orientation = PageOrientationType.Portrait; //设置打印区域 sheet.PageSetup.PrintArea = "B2:F8"; //打印标题 sheet.PageSetup.PrintTitleColumns = "$A:$B"; sheet.PageSetup.PrintTitleRows = "$1:$2"; //打印顺序 sheet.PageSetup.Order = OrderType.DownThenOver; sheet.PageSetup.Order = OrderType.OverThenDown; //设置打印对话框属性 PrintDialog dialog = new PrintDialog(); dialog.AllowPrintToFile = true; dialog.AllowCurrentPage = true; dialog.AllowSomePages = true; //设置单面打印 dialog.PrinterSettings.Duplex = Duplex.Simplex; //设置打印页面范围 dialog.PrinterSettings.FromPage = 0; dialog.PrinterSettings.ToPage = 8; dialog.PrinterSettings.PrintRange = PrintRange.SomePages; //设置打印份数 dialog.PrinterSettings.Copies = 5; //设置打印机名称 dialog.PrinterSettings.PrinterName = "HP LasterJet P1007"; //打印文档 workbook.PrintDialog = dialog; PrintDocument pd = workbook.PrintDocument; if (dialog.ShowDialog() == DialogResult.OK) { pd.Print(); }
【示例3】静默打印
//加载Excel文档 Workbook workbook = new Workbook(); workbook.LoadFromFile("Sample.xlsx"); //静默打印Excel文档 workbook.PrintDocument.PrintController = new StandardPrintController(); workbook.PrintDocument.Print();
(本文完)