Data binding is a useful feature that enables the user to work with data without needing complex code. In SpreadJS, the workbook can be bound to data and then displayed on a web page to give the user access to that data. To download the sample used in this blog, click here: SpreadJS Data Binding

Set Up the Project

Create a new empty ASP.NET Web project, and add a new html file in Visual Studio 2015. In this file, add references to the SpreadJS script and css files:


<!DOCTYPE html>  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head>  
    <meta charset="utf-8" />  
    <title>SpreadJS Data Binding</title>  

    <link href="http://cdn.grapecity.com/spreadjs/hosted/css/gcspread.sheets.excel2013white.9.40.20153.0.css" rel="stylesheet" type="text/css" />  
    <script type="text/javascript" src="http://cdn.grapecity.com/spreadjs/hosted/scripts/gcspread.sheets.all.9.40.20153.0.min.js"></script>  
</head>  
<body>  
</body>  
</html>  


Once this is done, add a script to the page that initializes the SpreadJS component as well as a div element to contain it:


<script>  
    window.onload = function() {  
        var spread = new GcSpread.Sheets.Spread(document.getElementById("spreadSheet"), { sheetCount: 1 });  
        var activeSheet = spread.getActiveSheet();  
    }  
</script>  
</head>  
<body>  
    <div id="spreadSheet" style="width: 100%; height: 550px; border: 1px solid gray"></div>  
</body>  

Load Data

SpreadJS can load data contained in a JSON file so that the user can manipulate it. In this example, the Spreadsheet is using a JSON file called ClassicCars.json, which contains data about different types of classic cars. To load this JSON into SpreadJS, first create a script function that will load the JSON from a file using an XLMHttpRequest:


function loadJSON(file, callback) {  
    var xobj = new XMLHttpRequest();  
    xobj.overrideMimeType("application/json");  
    xobj.open('GET', file, true);  
    xobj.onreadystatechange = function () {  
        if (xobj.readyState == 4 && xobj.status == "200") {  
            // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode  
            callback(xobj.responseText);  
        }  
    };  
    xobj.send(null);  
}  

Now implement that function, passing in the name of the file and a function for the callback parameter:


loadJSON("ClassicCars.json", function (response) {  
});  

Inside of that callback function, create a variable to hold the JSON data, and column information variables for each column in that data source:


var actual_JSON = JSON.parse(response);  
var nameColInfo = { name: "Name", displayName: "Name", size: "150" };  
var mpgColInfo = { name: "Miles\_per\_Gallon", displayName: "Miles/Gallon", size: "110" };  
var cylindersColInfo = { name: "Cylinders", displayName: "Cylinders", size: "100" };  
var displacementColInfo = { name: "Displacement", displayName: "Displacement (CI)", size: "140" };  
var horsepowerColInfo = { name: "Horsepower", displayName: "Horsepower", size: "120" };  
var weightColInfo = { name: "Weight\_in\_lbs", displayName: "Weight (lbs)", size: "110" };  
var accelerationColInfo = { name: "Acceleration", displayName: "Acceleration (sec.)", size: "140" };  
var yearColInfo = { name: "Year", displayName: "Year", size: "80" };  
var originColInfo = { name: "Origin", displayName: "Origin", size: "80" };  
var imageColInfo = { name: "Image", displayName: "Car Image", size: "330" };  

Then, set the data source of the SpreadJS instance to the JSON variable, and bind the columns to the column information variables that were created:


activeSheet.autoGenerateColumns = true;  
activeSheet.setDataSource(actual_JSON["Classic Cars"]);  
activeSheet.setRowHeaderVisible(false);  
activeSheet.bindColumn(0, nameColInfo);  
activeSheet.bindColumn(1, mpgColInfo);  
activeSheet.bindColumn(2, accelerationColInfo);  
activeSheet.bindColumn(3, cylindersColInfo);  
activeSheet.bindColumn(4, displacementColInfo);  
activeSheet.bindColumn(5, horsepowerColInfo);  
activeSheet.bindColumn(6, weightColInfo);  
activeSheet.bindColumn(7, yearColInfo);  
activeSheet.bindColumn(8, originColInfo);  
activeSheet.bindColumn(9, imageColInfo);  

This code successfully binds the data in the JSON file to the SpreadJS instance, and ensures that the columns in SpreadJS match up with the columns in the data source: The data-bound sheet without formatting. The data-bound sheet without formatting.

Format SpreadJS

Now that the data is in SpreadJS, the formatting can be changed to make the data look nicer. Create a new function to format the SpreadJS instance, and inside that function, add code to set the font, spacing, alignment, and borders for each row. In addition, set the background image of the cells in the ninth row from the URL provided in those cells:


function formatSpread() {  
    for (var i = 0; i < activeSheet.getRowCount() ; i++) {  
        activeSheet.getColumn(0).wordWrap(true);  
        activeSheet.getRow(i).font("12pt arial");  
        activeSheet.setRowHeight(i, 210);  
        activeSheet.getRow(i).borderBottom(new GcSpread.Sheets.LineBorder("Green", GcSpread.Sheets.LineStyle.thick));  
        if (activeSheet.getValue(i, 9) != null) {  
            var carImage = activeSheet.getValue(i, 9);  
            activeSheet.setValue(i, 9, null);  
            activeSheet.getCell(i, 9).backgroundImage(carImage);  
        }  
        activeSheet.getRow(i).vAlign(GcSpread.Sheets.VerticalAlign.center);  
        activeSheet.getRow(i).hAlign(GcSpread.Sheets.HorizontalAlign.center);  
    }  
}  

Next, add row filters for each row to allow the user to filter and sort on each column:


var cellRange = new GcSpread.Sheets.Range(0, 0, activeSheet.getRowCount(), 10);  
var hideRowFilter = new GcSpread.Sheets.HideRowFilter(cellRange);  
activeSheet.rowFilter(hideRowFilter);  

After that, add multiple column headers to help layout the data, and add a column range group to allow the user to minimize certain columns:


activeSheet.setRowCount(2, GcSpread.Sheets.SheetArea.colHeader);  

activeSheet.getColumn(0).borderRight(new GcSpread.Sheets.LineBorder("Green", GcSpread.Sheets.LineStyle.thin));  
activeSheet.setRowHeight(0, 30, GcSpread.Sheets.SheetArea.colHeader);  
activeSheet.addSpan(0, 1, 1, 2, GcSpread.Sheets.SheetArea.colHeader);  
activeSheet.getCell(0, 1, GcSpread.Sheets.SheetArea.colHeader).value("Fuel Economy & Acceleration");  
activeSheet.colRangeGroup.group(1, 2);  
activeSheet.getColumn(2).borderRight(new GcSpread.Sheets.LineBorder("Green", GcSpread.Sheets.LineStyle.thin));  

activeSheet.addSpan(0, 3, 1, 3, GcSpread.Sheets.SheetArea.colHeader);  
activeSheet.getCell(0, 3, GcSpread.Sheets.SheetArea.colHeader).value("Engine Details");  
activeSheet.addSpan(0, 6, 1, 4, GcSpread.Sheets.SheetArea.colHeader);  
activeSheet.getCell(0, 6, GcSpread.Sheets.SheetArea.colHeader).value("Car Details");  
activeSheet.getColumn(5).borderRight(new GcSpread.Sheets.LineBorder("Green", GcSpread.Sheets.LineStyle.thin));  

activeSheet.setRowHeight(1, 30, GcSpread.Sheets.SheetArea.colHeader);  

var headerStyle = new GcSpread.Sheets.Style();  
headerStyle.backColor = "Green";  
headerStyle.foreColor = "White";  
headerStyle.hAlign = GcSpread.Sheets.HorizontalAlign.center;  
headerStyle.vAlign = GcSpread.Sheets.VerticalAlign.center;  

for (var i = 0; i < activeSheet.getColumnCount() ; i++) {  
    activeSheet.setStyle(0, i, headerStyle, GcSpread.Sheets.SheetArea.colHeader);  
    activeSheet.setStyle(1, i, headerStyle, GcSpread.Sheets.SheetArea.colHeader);  
}  

That code completes the formatting function implementation. Add a call to that function from within the callback function for loading the JSON, to ensure the SpreadJS instance gets formatted once the data is loaded:


//...  
activeSheet.bindColumn(9, imageColInfo);  

formatSpread();  

spread.isPaintSuspended(false);  

Once that is done, the SpreadJS instance will be formatted to layout the data in a user-friendly manner. This tutorial showed how to bind data to SpreadJS, as well as how to format that data to provide additional functionality to the user. The data-bound sheet with formatting. The data-bound sheet with formatting.