Spread.Sheets supports serialization of custom cell types, custom functions, custom formatters, custom tags, and custom sparklineEx.
When serialized, a custom type's toJSON method stores a string field type that indicates itself. The string type is related to the window, such as "mynamespace.MyCellType". When deserialized, the getTypeFromString method gets the custom type by parsing the type string, then creates an instance of the custom type, and then invokes the fromJSON method of the instance.
If you assign the actual type string to the type field of a custom type, the custom type is serialized and deserialized. If a custom type has a circular dependency or you want to reduce the JSON size or have some other requirement, the custom type also needs to override the toJSON and fromJSON methods.
If you do not want to put the custom type on a window object, you also need to override the getTypeFromString method for parsing the type string.
This example uses spread1’s toJSON and spread2’s fromJSON function to implement serializing all data from spread1 to spread2. The “MyTag” instance is on spread2 after selecting the button.
JavaScript |
Copy Code
|
---|---|
<!DOCTYPE html> <html> <head> <title>Spread HTML test page</title> <link type="text/css" href="./css/gc.spread.sheets.11.0.0.css" rel="stylesheet" /> <script src="http://code.jquery.com/jquery-2.0.2.js" type="text/javascript"></script> <script type="text/javascript" src="./scripts/gc.spread.sheets.all.11.0.0.min.js"></script> <script type="text/javascript"> //Custom tag function MyTag(name, age) { this.name = name; this.age = age; this.typeName = "MyTag"; } MyTag.prototype.toJSON = function () { var settings = {}; settings.name = this.name; settings.age = this.age; settings.typeName = this.typeName; return settings; }; MyTag.prototype.fromJSON = function (settings) { this.name = settings.name; this.age = settings.age; this.typeName = settings.typeName; }; $(function () { var spread1 = new GC.Spread.Sheets.Workbook(document.getElementById("ss"),{sheetCount:3}); var sheet1 = spread1.getActiveSheet(); sheet1.tag(new MyTag("Ivy", 24)); sheet1.setTag(0, 0, new MyTag("Yang", 25)); $("#btn1").click(function () { //Serialize ss to ss1. var jsonStr = JSON.stringify(spread1.toJSON()); var spread2 = new GC.Spread.Sheets.Workbook(document.getElementById("ss1"),{sheetCount:3}); spread2.fromJSON(JSON.parse(jsonStr)); var sheet2 = spread2.getActiveSheet(); alert("Tag of sheet:" + JSON.stringify(sheet2.tag())); alert("Tag of Cell[0,0]: " + JSON.stringify(sheet2.getTag(0, 0))); }); }); </script> </head> <body> <div> <div id="ss" style="height: 200px; width: 500px"></div> <div id="ss1" style="height: 200px; width: 500px"></div> </div> <input type="button" id="btn1" value="Serialization" /> </body> </html> |