C# 设置Excel打印选项及打印excel文档
打印Excel文档是一个很常见的操作,但有时候我们会碰到各种不同的打印需求,例如只打印一个Excel工作表的其中一部分,或打印时每页都有表头,或把工作表中超出1页所有内容打印到1页上等等,这时我们需要对Excel的打印选项进行设置。这篇文章主要是分享如何使用Excel组件及C#来设置一些常见的Excel打印选项及打印Excel文档。
下面这个Excel工作表共含有17行,20列数据:
目标:将第7, 8行的所有数据打印到一页上,并打印表头(标题行)。
创建一个WinForm项目,使用如下命名空间:
using System; using System.Drawing.Printing; using System.Windows.Forms; using Spire.Xls;
步骤1:创建一个新的workbook对象并加载Excel文档。
Workbook workbook = new Workbook(); workbook.LoadFromFile("Sample.xlsx");
步骤2:获取该Excel文档的第一个工作表,并设置打印选项。
Worksheet sheet = workbook.Worksheets[0];
下面列出几个常设置的打印选项:
设置打印区域/范围:
sheet.PageSetup.PrintArea = "A7:T8";
设置打印表头(标题行):
sheet.PageSetup.PrintTitleRows = "$1:$1";
设置excel工作表缩放为一页宽一页高:
sheet.PageSetup.FitToPagesWide = 1; sheet.PageSetup.FitToPagesTall = 1;
这里可以设置它们的值为0或1来改变打印效果以满足不同需求。
除此之外还可以设置页面方向及打印页面大小等:
设置页面方向:
sheet.PageSetup.Orientation = PageOrientationType.Portrait;
设置打印页面大小:
sheet.PageSetup.PaperSize = PaperSizeType.PaperA3;
步骤3:创建一个新的PrintDialog对象,设置dialog属性及打印页面范围并打印文档。
PrintDialog dialog = new PrintDialog(); dialog.AllowPrintToFile = true; dialog.AllowCurrentPage = true; dialog.AllowSomePages = true; dialog.AllowSelection = true; dialog.UseEXDialog = true; dialog.PrinterSettings.Duplex = Duplex.Simplex; dialog.PrinterSettings.FromPage = 0; dialog.PrinterSettings.ToPage = 8; dialog.PrinterSettings.PrintRange = PrintRange.SomePages; workbook.PrintDialog = dialog; PrintDocument pd = workbook.PrintDocument; if (dialog.ShowDialog() == DialogResult.OK) { pd.Print(); }
运行程序会出现如下对话框:
这里我选择Microsoft XPS Document Writer将这个excel文档打印为XPS格式,得到的XPS文件如下:
全部代码:
using System; using System.Drawing.Printing; using System.Windows.Forms; using Spire.Xls; namespace Print_Excel_in_csharp { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Workbook workbook = new Workbook(); workbook.LoadFromFile("Sample.xlsx"); Worksheet sheet = workbook.Worksheets[0]; sheet.PageSetup.PrintArea = "A7:T8"; sheet.PageSetup.PrintTitleRows = "$1:$1"; sheet.PageSetup.FitToPagesWide = 1; sheet.PageSetup.FitToPagesTall = 1; //sheet.PageSetup.Orientation = PageOrientationType.Landscape; //sheet.PageSetup.PaperSize = PaperSizeType.PaperA3; PrintDialog dialog = new PrintDialog(); dialog.AllowPrintToFile = true; dialog.AllowCurrentPage = true; dialog.AllowSomePages = true; dialog.AllowSelection = true; dialog.UseEXDialog = true; dialog.PrinterSettings.Duplex = Duplex.Simplex; dialog.PrinterSettings.FromPage = 0; dialog.PrinterSettings.ToPage = 8; dialog.PrinterSettings.PrintRange = PrintRange.SomePages; workbook.PrintDialog = dialog; PrintDocument pd = workbook.PrintDocument; if (dialog.ShowDialog() == DialogResult.OK) { pd.Print(); } } } }