Live Razor Page Samples

Basic Chart

This sample shows how to create a new workbook, add some values, add a chart, and stream it to Microsoft Excel.
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace Website.Pages.Support.Samples.RazorPages.Charting
{
    public partial class BasicChartModel : PageModel
    {
        public FileResult OnGet()
        {
            // Create a new workbook.
            SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook();
            SpreadsheetGear.IWorksheet worksheet = workbook.Worksheets["Sheet1"];
            SpreadsheetGear.IWorksheetWindowInfo windowInfo = worksheet.WindowInfo;

            // Load some sample data.
            SpreadsheetGear.IRange dataRange = worksheet.Cells["A2:A13"];
            dataRange.Formula = "=INT(RAND() * 10 + 5)";

            // Add a chart to the worksheet's shape collection.
            // NOTE: Calculate the coordinates of the chart by converting row
            //       and column coordinates to points.  Use fractional row 
            //       and colum values to get coordinates anywhere in between 
            //       row and column boundaries.
            double left = windowInfo.ColumnToPoints(2.0);
            double top = windowInfo.RowToPoints(1.0);
            double right = windowInfo.ColumnToPoints(9.0);
            double bottom = windowInfo.RowToPoints(16.0);
            SpreadsheetGear.Charts.IChart chart =
                worksheet.Shapes.AddChart(left, top, right - left, bottom - top).Chart;

            // Set the chart's source data range, plotting series in columns.
            chart.SetSourceData(dataRange, SpreadsheetGear.Charts.RowCol.Columns);

            // Set the chart type.
            chart.ChartType = SpreadsheetGear.Charts.ChartType.Area;

            // 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-BasicChart.xlsx";
            return File(workbookStream, contentType, fileName);
        }
    }
}