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(); } } } }
