Search code examples
c#excelprintingspreadsheetgear

Print excel (generated using Spreadsheetgear) in C#


In c# i am generating an excel in specific format, i have to print the same excel format on click_print.

P.s.-Microsoft Office not available,using SpreadSheetGear for this.


Solution

  • I recommend Chuck's answer if you have a UI and are utilizing the WorkbookView control. If you are generating this workbook in-code without a UI, you can also print a workbook by using the WorkbookPrintDocument class. Below is an example that demonstrates this in a console application:

    using SpreadsheetGear;
    using SpreadsheetGear.Printing;
    using SpreadsheetGear.Drawing.Printing;
    
    static void Main(string[] args)
    {
        // Create a workbook with some cell data
        IWorkbook workbook = Factory.GetWorkbook();
        IWorksheet worksheet = workbook.ActiveWorksheet;
        IRange cells = worksheet.Cells;
        cells["A1:D10"].Value = "=RAND()";
    
        // Create a WorkbookPrintDocument.  
        WorkbookPrintDocument printDocument = new WorkbookPrintDocument(worksheet, PrintWhat.Sheet);
    
        // Set the printer if necessary...let's go old school.
        printDocument.PrinterSettings.PrinterName = "Epson MX-80";
    
        // Print it
        printDocument.Print();
    }
    

    If you are using the .NET 4.0 build of SpreadsheetGear 2012, you'll need to add a reference to the SpreadsheetGear2012.Drawing.dll assembly to access the SpreadsheetGear.Drawing.Printing namespace.

    Also note that I specify to print (the used range of) the sheet via PrintWhat.Sheet. See the SpreadsheetGear.Printing.PrintWhat enum for more options.