Live Razor Page Samples

Excel Report with Chart (From Template Workbook)

This sample shows how to load a workbook containing a chart, add some values, and stream it to Microsoft Excel.

Supporting Files

The following file is utilized by this sample:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace Website.Pages.Support.Samples.RazorPages.Reporting
    public partial class ExcelReportWithChartFromTemplateModel : PageModel
        public FileResult OnGet()
            // Open a workbook template containing a chart
            SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook("files/chartsimple.xlsx");
            SpreadsheetGear.IWorksheet worksheet = workbook.Worksheets["2020 Sales"];

            // Load random data and format as $ using a multiple cell range.
            SpreadsheetGear.IRange body = worksheet.Cells[1, 1, 4, 4];
            body.Formula = "=400000 + (RAND() * 200000)";
            body.NumberFormat = "$#,##0_);($#,##0)";

            // Save workbook to stream using the Open XML (*.xlsx) file format compatible with Excel 2007 and later.
            System.IO.Stream workbookStream = workbook.SaveToStream(SpreadsheetGear.FileFormat.OpenXMLWorkbook);

            // Reset position to beginning of stream.
            workbookStream.Seek(0, System.IO.SeekOrigin.Begin);

            // Stream the Excel workbook to the client.
            var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            var fileName = "SpreadsheetGear-Sample-ExcelReportWithChartFromTemplate.xlsx";
            return File(workbookStream, contentType, fileName);