Quantcast
Channel: Spread Help » Spread
Viewing all 105 articles
Browse latest View live

Spread.Views and the Trellis Layout

$
0
0

If you want to create a card style layout that can be used to collaborate with others or to keep track of a process, the Trellis view in Spread.Views may be just what you need.

The following example uses a Trellis view for keeping track of a bid process. Use the following steps to create the example:

  1. Add the following references to your page. The gridLayoutEngine reference is used for a basic grid. The trellisStrategy reference is required for a Trellis view.
    <link rel="stylesheet" type="text/css" href="dataview.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/zepto/1.1.6/zepto.min.js" type="text/javascript"></script>
    <script src="dataview.min.js" type="text/javascript"></script>
    <script src="plugins/gridLayoutEngine.min.js" type="text/javascript"></script>
    <script src="plugins/trellisStrategy.min.js" type="text/javascript"></script>
  2. Set the styles and colors for the items in the Trellis view and the height and width for the grid.
    html {
    position: fixed;
    width: 100%;
    }
    .group-item-title {
    border: none;
    color: #f1f1f1;
    background: #C48C43;
    white-space: nowrap;
    text-overflow: ellipsis;
    padding: 0.4em;
    font-size: 16px;
    }
    .group-item-description {
    padding: 8px;
    }
    .gc-trellis-group-header-inner {
    padding: 0 0.4em;
    font-size: 16px;
    }
    .group-item-container {
    height: 100%;
    font-size: 12px;
    overflow: hidden;
    position: relative;
    }
    .group-item-container-inner {
    height: 95%;
    border-radius: 4px;
    overflow: hidden;
    color: #f1f1f1;
    box-shadow: 0 3px 5px rgba(0, 0, 0, 0.10);
    }
    .finish {
    background: #603E50;
    }
    .eighty-per {
    background: #695877;
    }
    .fifty-per {
    background: #73738E;
    }
    .thirty-per {
    background: #7C9EAA;
    }
    .start {
    background: #8FC8C9;
    }
    .finish-head {
    background: #533747;
    }
    .eighty-per-head {
    background: #5F506B;
    }
    .fifty-per-head {
    background: #6A6B83;
    }
    .thirty-per-head {
    background: #76949F;
    }
    .firstcol {
    background: #C0C0C0;
    }
    .firstcol-header {
    background: #808080;
    }
    .four {
    background: #C0C0C0;
    }
    .four-header {
    background: #808000;
    }
    .start-head {
    background: #86BBBD;
    }
    .trellis-strategy .gc-trellis-group-header {
    line-height: 24px;
    }
    </style>
    </head>
    <body style="margin:0;position:absolute;top:0;bottom:0;left:0;right:0;font-size:14px;">
    <div style="height: 100%; position: relative">
    <div style="height:90%;">
    <div id="grid1" style="height:100%;"></div>
    </div>
    </div>
  3. Define variables for dataView and trellisStrategy.
    var dataView;
    var trellisStrategy;
  4. Create a row template and use a range of values to assign a color to the card item.
    var rowTemplate = '<div class="group-item-container">' +
    '<div class="group-item-container-inner {{? it.progress==100}}finish{{?? it.progress>=80}}eighty-per{{?? it.progress>=50}}fifty-per{{?? it.progress>=40}}four{{?? it.progress>=30}}thirty-per{{?? it.progress>=20}}
    firstcol{{??}}start{{?}}">' +
    '<div data-column="title" class="group-item-title {{? it.progress==100}}finish-head{{?? it.progress>=80}}eighty-per-head{{?? it.progress>=50}}fifty-per-head{{?? it.progress>=40}}four-header{{?? it.progress>=30}}
    thirty-per-head{{?? it.progress>=20}}firstcol-header{{??}}start-head{{?}}"></div>' +
    '<div data-column="description" class="group-item-description"></div>' +
    '</div></div>';
  5. Specify the column items from the JSON file.
    var columns = [{
    id: 'title',
    name: 'title',
    dataField: 'title'
    }, {
    id: 'description',
    name: 'description',
    dataField: 'description'
    }, {
    id: 'progress',
    dataField: 'progress'
    }];
  6. Specify the file to get the data from.
    $.getJSON('trellisviewdatafile.json', function(data)
  7. Create a trellis strategy.
    {
    trellisStrategy = new GC.Spread.Views.DataView.Plugins.TrellisStrategy({
    panelUnitWidth: 190
    });
  8. Create a basic view.
    dataView = new GC.Spread.Views.DataView(document.getElementById('grid1'), data, columns, new GC.Spread.Views.DataView.Plugins.GridLayoutEngine
  9. Create a group strategy and specify the items in the group.
    grouping: [{
    field: 'work',
    header: {
    height: 24
    }
    }, {
    field: 'category',
    header: {
    height: 24
    }
    }],
  10. Assign the row template and set the group strategy to the trellis strategy.
    rowTemplate: rowTemplate,
    rowHeight: 120,
    groupStrategy: trellisStrategy

That is all you need to create a Trellis view in Spread.Views.

You can download a CTP of Spread.Views here: http://spread.grapecity.com/spreadjs/views/.

SpreadViewsTrellis

Trellis View

Here is the complete code example:

<!doctype html>
<html style="height:100%;font-size:14px;">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" type="text/css" href="dataview.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/zepto/1.1.6/zepto.min.js" type="text/javascript"></script>
<script src="dataview.min.js" type="text/javascript"></script>
<script src="plugins/gridLayoutEngine.min.js" type="text/javascript"></script>
<script src="plugins/trellisStrategy.min.js" type="text/javascript"></script>
<style>
html {
position: fixed;
width: 100%;
}
.group-item-title {
border: none;
color: #f1f1f1;
background: #C48C43;
white-space: nowrap;
text-overflow: ellipsis;
padding: 0.4em;
font-size: 16px;
}
.group-item-description {
padding: 8px;
}
.gc-trellis-group-header-inner {
padding: 0 0.4em;
font-size: 16px;
}
.group-item-container {
height: 100%;
font-size: 12px;
overflow: hidden;
position: relative;
}
.group-item-container-inner {
height: 95%;
border-radius: 4px;
overflow: hidden;
color: #f1f1f1;
box-shadow: 0 3px 5px rgba(0, 0, 0, 0.10);
}
.finish {
background: #603E50;
}
.eighty-per {
background: #695877;
}
.fifty-per {
background: #73738E;
}
.thirty-per {
background: #7C9EAA;
}
.start {
background: #8FC8C9;
}
.finish-head {
background: #533747;
}
.eighty-per-head {
background: #5F506B;
}
.fifty-per-head {
background: #6A6B83;
}
.thirty-per-head {
background: #76949F;
}
.firstcol {
background: #C0C0C0;
}
.firstcol-header {
background: #808080;
}
.four {
background: #C0C0C0;
}
.four-header {
background: #808000;
}
.start-head {
background: #86BBBD;
}
.trellis-strategy .gc-trellis-group-header {
line-height: 24px;
}
</style>
</head>
<body style="margin:0;position:absolute;top:0;bottom:0;left:0;right:0;font-size:14px;">
<div style="height: 100%; position: relative">
<div style="height:90%;">
<div id="grid1" style="height:100%;"></div>
</div>
</div>
<script type="text/javascript">
var dataView;
var trellisStrategy;
var rowTemplate = '<div class="group-item-container">' +
'<div class="group-item-container-inner {{? it.progress==100}}finish{{?? it.progress>=80}}eighty-per{{?? it.progress>=50}}fifty-per{{?? it.progress>=40}}four{{?? it.progress>=30}}thirty-per{{?? it.progress>=20}}firstcol{{??}}start{{?}}">' +
'<div data-column="title" class="group-item-title {{? it.progress==100}}finish-head{{?? it.progress>=80}}eighty-per-head{{?? it.progress>=50}}fifty-per-head{{?? it.progress>=40}}four-header{{?? it.progress>=30}}thirty-per-head{{?? it.progress>=20}}firstcol-header{{??}}start-head{{?}}"></div>' +
'<div data-column="description" class="group-item-description"></div>' +
'</div></div>';
var columns = [{
id: 'title',
name: 'title',
dataField: 'title'
}, {
id: 'description',
name: 'description',
dataField: 'description'
}, {
id: 'progress',
dataField: 'progress'
}];
$(document).ready(function() {
$.getJSON('trellisviewdatafile.json', function(data) {
trellisStrategy = new GC.Spread.Views.DataView.Plugins.TrellisStrategy({
panelUnitWidth: 190
});
dataView = new GC.Spread.Views.DataView(document.getElementById('grid1'), data, columns, new GC.Spread.Views.DataView.Plugins.GridLayoutEngine({
grouping: [{
field: 'work',
header: {
height: 24
}
}, {
field: 'category',
header: {
height: 24
}
}],
rowTemplate: rowTemplate,
rowHeight: 120,
groupStrategy: trellisStrategy
}));
})
});
</script>
</body>
</html>

You can download the data file from here: trellisviewdatafile.


SpreadJS and TypeScript

$
0
0

For some developers, working with TypeScript provides better tools and options than just JavaScript by itself. SpreadJS script code can be written in TypeScript to provide that enhanced functionality in conjunction with the power of SpreadJS. In this blog, you will learn how to use TypeScript in place of JavaScript code to implement SpreadJS functionality.

The download for this sample can be found here: TypeScriptHTMLAPP_SpreadJS

The finished TypeScript page.

The finished TypeScript page.

Set Up the Project

Start off by creating an empty ASP.NET web application in Visual Studio 2015. Once the project has been created, add a page with a DIV element for SpreadJS on it:


<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>TypeScript HTML App</title>
    <link href="http://cdn.grapecity.com/spreadjs/hosted/css/gcspread.sheets.excel2013white.9.40.20161.0.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="http://cdn.grapecity.com/spreadjs/hosted/scripts/gcspread.sheets.all.9.40.20161.0.min.js"></script>
</head>
<body>
    <h1>TypeScript HTML App</h1>

    <div id="content">
        <div id="ss" style="width:700px;height:400px;border:1px solid gray"></div>
    </div>
</body>
</html>

Add TypeScript

For information on how to add TypeScript with SpreadJS, see this documentation link:

http://sphelp.grapecity.com/webhelp/SpreadJSWeb/webframe.html#typescript.html

As described in the link above, add the SpreadJS TypeScript definition file:

The TypeScript definition file in the Solution Explorer.

The TypeScript definition file in the Solution Explorer.

Then add a file to the project to contain the TypeScript code called “app.ts”, and reference that file you just added:


/// <reference path="definition/gcspread.sheets.d.ts" />

Now script code can be added to the “app.ts” file just as you would normal JavaScript code:


window.onload = () => {
    var spread = new GcSpread.Sheets.Spread(document.getElementById("ss"));
    var sheet = spread.getActiveSheet();
    sheet.setRowHeight(3, 100);
    sheet.setColumnWidth(3, 100);
    sheet.getCell(3, 3).wordWrap(true).value("SpreadJS\nTypeScript");
};

In the web page, add a reference to this new TypeScript file with your code in it:


<head>
    <meta charset="utf-8" />
    <title>TypeScript HTML App</title>
    <link href="http://cdn.grapecity.com/spreadjs/hosted/css/gcspread.sheets.excel2013white.9.40.20161.0.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="http://cdn.grapecity.com/spreadjs/hosted/scripts/gcspread.sheets.all.9.40.20161.0.min.js"></script>
    <script src="app.ts"></script>
</head>

If done correctly, the TypeScript code should compile to JavaScript and show the SpreadJS element with the changes made from the TypeScript code:

The finished TypeScript page.

The finished TypeScript page.

Since TypeScript code compiles to generic JavaScript code, the result runs just like normal JavaScript code with SpreadJS. This tutorial showed how to use TypeScript code with SpreadJS to provide strongly-typed access and better information about the code when developing.

Spread Windows Forms Designer and Sparklines

$
0
0

You can use the Spread Windows Forms designer to quickly design a sparkline.

Start the Spread Designer by selecting the FarPoint.SpreadDesigner.EXE from the product bin folder or by right-clicking on the FpSpread component on your form and then choosing Spread Designer.

You can create a sparkline using the following steps:

      1. Add data to the designer.
        SpreadWinDesignerSparkTest

        Data

      2. Select the Insert tab.
        SpreadWinDesignerInsert

        Insert Tab

      3. Select a sparkline type (Sparklines section). The Create Sparklines dialog is displayed.
        SpreadWinDesignerAddSpark

        Sparkline Type

      4. Specify the data range and the sparkline location.
        SpreadWinDesignerSparkRange

        Sparkline Range and Location

      5. The Sparklines tab is displayed once you select a type.
        SpreadWinDesignerSOptions

        Sparkline Options

      6. The following options are available:
        Item Description
        Edit Data This option allows you to change the sparkline data.
        Line, Column, or Win/Loss This option allows you to change the type of sparkline.
        High Point This option specifies whether to display the point for the largest value.
        Low Point This option specifies whether to display the point for the smallest value.
        Negative Point This option specifies whether to display points for negative values.
        First Point This option specifies whether to display the first point on the graph.
        Last Point This option specifies whether to display the last point on the graph.
        Markers This option specifies whether to add points for all the data (only applies to the line sparkline).
        Sparkline Color This option specifies the line color for the line sparkline or the data point color for the column or winloss sparkline.
        Marker Color This option specifies the color of the data points for the line sparkline or the color of the special data points for the column or winloss sparkline (for example, first point).
        Weight This option specifies the thickness of the line for the line sparkline.
        Axis This option specifies the axis type, how the data is plotted, whether to display an axis, and the minimum and maximum settings for the vertical axis. The horizontal axis is only displayed if the data contains negative values.
        Group This option allows you to group selected sparklines so they can share formatting and scaling options
        Ungroup This option removes the grouping from selected sparklines.
        Clear This option clears the selected sparklines.

        If the chart type is column or winloss, then selecting point options changes the color of the point indicator. Selecting point options with the line sparkline adds a data point to the line.

      7. Specify the sparkline options to complete your sparkline.
        SpreadWinDesignerSparkOptions

        Completed Sparklines

For more information about sparklines, refer to: http://sphelp.grapecity.com/WebHelp/SpreadNet9/WF/webframe.html#spwin-sparklines.html.

SpreadJS Rich Text

$
0
0

SpreadJS provides different cell types that give the user useful functionality. Rich text formatting is something that isn’t supported out-of-the-box in SpreadJS, but a custom HTML Cell Type can be implemented that provides most of the functionality of general HTML tags inside of cells in SpreadJS.

Download the source code for this tutorial: SpreadJS RichText

The finished SpreadJS instance with HTML Cell Types

The finished SpreadJS instance with HTML Cell Types

Set Up the Project


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>SpreadJS Rich Text</title>
    <!--jQuery References-->
    <script src="http://code.jquery.com/jquery-1.9.1.min.js" type="text/javascript"></script>

    <link href="http://cdn.grapecity.com/spreadjs/hosted/css/gcspread.sheets.excel2013white.9.40.20161.0.css" rel="stylesheet" type="text/css" />

    <script type="text/javascript" src="http://cdn.grapecity.com/spreadjs/hosted/scripts/gcspread.sheets.all.9.40.20161.0.min.js"></script>

    <script type="text/javascript">
        // Initialize SpreadJS
        $(document).ready(function () {
            var spread = new GcSpread.Sheets.Spread(document.getElementById("ss"));
            var sheet = spread.getActiveSheet();
Text</strong>');
        });
    </script>
</head>
<body>
    <div id="ss" style="width: 550px; height: 400px; border: 1px solid gray"></div>
</body>
</html>

Code the Custom Cell Type

To implement rich text functionality, we are going to create a custom HTML Cell Type that uses the built-in TextCellType as a base:


function HTMLCellType() { }
HTMLCellType.prototype = new GcSpread.Sheets.TextCellType();

In this example, the main function we will be implementing is the paint function, since the functionality revolves around how the cell type paints. To start implementing the paint function, initialize the variable that will be used:


HTMLCellType.prototype.paint = function (ctx, value, x, y, w, h, style, context) {
    var DOMURL = window.URL || window.webkitURL || window;
    var cell = context.sheet.getCell(context.row, context.col);
    var img = cell.tag();
};

The HTML Cell Type takes an SVG image created from XML code and sets it as the tag for the cell. The tag is then applied to the cell via the ctx variable, which is the CanvasRenderingContext. The beginning part of the paint function will check if the cell’s tag exists and then paint the SVG image in the cell:


if (img) {
    ctx.save();
    ctx.rect(x, y, w, h);
    ctx.clip();
    ctx.drawImage(img, x + 2, y + 2)
    DOMURL.revokeObjectURL(url);
    ctx.restore();
    cell.tag(null);
    return;
}

The next part to implement is setting up the content to create the SVG from. In this case, use a pattern and replace specific data in it with information from the cell’s data. Then create XML from that:


var svgPattern = '<svg xmlns="http://www.w3.org/2000/svg" width="{0}" height="{1}">' +
    '<foreignObject width="100%" height="100%"><div xmlns="http://www.w3.org/1999/xhtml" style="font:{2}">{3}</div></foreignObject></svg>';

var data = svgPattern.replace("{0}", w).replace("{1}", h).replace("{2}", style.font).replace("{3}", value);
var doc = document.implementation.createHTMLDocument("");
doc.write(data);
// Get well-formed markup
data = (new XMLSerializer()).serializeToString(doc.body.children[0]);

The last part of the implementation is to create the image from the SVG and set it as the cell’s tag property, which will be used when painting:


img = new Image();
img.crossOrigin = "";
var svg = new Blob([data], {
    type: 'image/svg+xml;charset=utf-8'
});
var url = DOMURL.createObjectURL(svg);
img.src = url;
cell.tag(img);
img.onload = function () {
    context.sheet.repaint(new GcSpread.Sheets.Rect(x, y, w, h));
}

Now that the HTML Cell Type has been implemented, we can set it with the cellType property on cells in the sheet, and specify the value as HTML code:


$(document).ready(function () {
    var spread = new GcSpread.Sheets.Spread(document.getElementById("ss"));
    var sheet = spread.getActiveSheet();
    sheet.getColumn(0).width(125);
    sheet.getRow(0).height(30);
    sheet.getCell(0, 0).cellType(new HTMLCellType()).value('<sup>Supercript</sup>Test<sub>Subscript</sub>');
    sheet.getCell(0, 1).cellType(new HTMLCellType()).value('<font color="#FF0000">Red Text</font>');
    sheet.getColumn(2).width(125);
    sheet.getCell(0, 2).cellType(new HTMLCellType()).value('<font style="font-family:courier;">Courier Font</font>');
    sheet.getCell(0, 3).cellType(new HTMLCellType()).value('<strong>Bold Text</strong>');
    sheet.getRow(1).height(50);
    sheet.getCell(1, 0).cellType(new HTMLCellType()).value('<h1>Heading</h1>');
});

This will show the resulting HTML inside the cells as if it was just running on the page, and the user can edit the actual HTML code by entering edit mode on the cells.

The HTML Cell Type in Edit Mode

The HTML Cell Type in Edit Mode.

Spread.Views and the Timeline Layout

$
0
0

A Timeline layout can make your data easier to follow. This can be particularly useful for milestones in a project or a meeting schedule.

Use the following steps to create a timeline that displays a meeting schedule.

1. Add the following references to your page. The gridLayoutEngine reference is used for a basic grid. The timelineStrategy reference is required for a Timeline view.

<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" type="text/css" href="dataview.css">
<link rel="stylesheet" type="text/css" href="plugins/timelineStrategy.css">
<script src="dataview.min.js" type="text/javascript"></script>
<script src="plugins/gridLayoutEngine.min.js" type="text/javascript"></script>
<script src="plugins/timelineStrategy.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/zepto/1.1.6/zepto.min.js" type="text/javascript"></script>

2. Add any formatting and the height and width for the grid on the page.

<style>
* {
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
.gc-grid {
border: 1px none white;
}
</style>
</head>
<body style="margin:0;position:absolute;top:0;bottom:0;left:0;right:0;font-size:14px;user-select:none;-webkit-user-select: none;">
<div style="height: 100%; position: relative">
<div id="gridContainer" style="height:620px;">
<div id="grid1" style="height:100%;position: relative"></div>
</div>

3. Define variables for the data view and strategy.

var dataView;
var timeLinestrategy;

4. Specify the column items from the JSON file.

var columns = [{
id: 'topic',
dataField: 'topic'
}, {
id: 'start',
dataField: 'start',
format: 'MMMM dd, HH:mmtt'
}, {
id: 'end',
dataField: 'end',
format: 'HH:mm tt'
}, {
id: 'speaker',
dataField: 'speaker'
}, {
id: 'content',
dataField: 'content'
}];

5. Create a template.

var groupDetailEventTemplate = '<div style="margin:5px;">' +
'<div style="font-size:14px;font-weight: bold;">{{=it.topic}}</div>' +
'<blockquote style="padding-left: 15px;display: block;font-size:13px;font-family: "Helvetic Neue, Helvetica, Arial">{{=it.content}}</blockquote>' +
'<span style="margin-right: auto" >{{=it.start}}</span>' +
'</div>';

6. Specify the JSON file to get data from.

$.getJSON('timeline.json', function(data) {

7. Check to see if the start and end dates in the data match.

$.each(data, function(key, val) {
for (var prop in val) {
if (prop === 'start' || prop === 'end') {
val[prop] = new Date(val[prop]);
}
}

8. Create a formatter to handle the dates.

var excelFormatter = new GC.Spread.Views.DataView.Plugins.Formatter.ExcelFormatter('mmmm dd');

9. Assign the timeline strategy variable.

timeLinestrategy = new GC.Spread.Views.DataView.Plugins.TimelineStrategy({});

10. Create the data view, specify the group by field, and specify the templates to use for the rows and timeline group.

dataView = new GC.Spread.Views.DataView(document.getElementById('grid1'), data, columns, new
GC.Spread.Views.DataView.Plugins.GridLayoutEngine({
grouping: {
field: 'start',
converter: function(field) {
return excelFormatter.format(field);
}
},
autoRowHeight: true,
rowTemplate: groupDetailEventTemplate,
groupStrategy: timeLinestrategy
}));

That is all you need to do to create a Timeline view in Spread.Views. Here is the complete example.

timeline

<!doctype html>
<html style="height:100%;font-size:14px;">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" type="text/css" href="dataview.css">
<link rel="stylesheet" type="text/css" href="plugins/timelineStrategy.css">
<script src="dataview.min.js" type="text/javascript"></script>
<script src="plugins/gridLayoutEngine.min.js" type="text/javascript"></script>
<script src="plugins/timelineStrategy.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/zepto/1.1.6/zepto.min.js" type="text/javascript"></script>
<style>
* {
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
.gc-grid {
border: 1px none white;
}
</style>
</head>
<body style="margin:0;position:absolute;top:0;bottom:0;left:0;right:0;font-size:14px;user-select:none;-webkit-user-select: none;">
<div style="height: 100%; position: relative">
<div id="gridContainer" style="height:620px;">
<div id="grid1" style="height:100%;position: relative"></div>
</div>
</div>
<script type="text/javascript">
var dataView;
var timeLinestrategy;
var columns = [{
id: 'topic',
dataField: 'topic'
}, {
id: 'start',
dataField: 'start',
format: 'MMMM dd, HH:mmtt'
}, {
id: 'end',
dataField: 'end',
format: 'HH:mm tt'
}, {
id: 'speaker',
dataField: 'speaker'
}, {
id: 'content',
dataField: 'content'
}];
var groupDetailEventTemplate = '<div style="margin:5px;">' +
'<div style="font-size:14px;font-weight: bold;">{{=it.topic}}</div>' +
'<blockquote style="padding-left: 15px;display: block;font-size:13px;font-family: "Helvetic Neue, Helvetica, Arial">{{=it.content}}</blockquote>' +
'<span style="margin-right: auto" >{{=it.start}}</span>' +
'</div>';
$(document).ready(function() {
$.getJSON('timeline.json', function(data) {
$.each(data, function(key, val) {
for (var prop in val) {
if (prop === 'start' || prop === 'end') {
val[prop] = new Date(val[prop]);
}
}
});
var excelFormatter = new GC.Spread.Views.DataView.Plugins.Formatter.ExcelFormatter('mmmm dd');
//triangle
timeLinestrategy = new GC.Spread.Views.DataView.Plugins.TimelineStrategy({});
dataView = new GC.Spread.Views.DataView(document.getElementById('grid1'), data, columns, new GC.Spread.Views.DataView.Plugins.GridLayoutEngine({
grouping: {
field: 'start',
converter: function(field) {
return excelFormatter.format(field);
}
},
autoRowHeight: true,
rowTemplate: groupDetailEventTemplate,
groupStrategy: timeLinestrategy
}));
});
});
</script>
</body>
</html>

You can download the JSON file here: timeline.

You can download a CTP of Spread.Views here: http://spread.grapecity.com/spreadjs/views/.

SpreadJS V10 Fixed Bugs

$
0
0

In this article, you will find all of the SpreadJS bugs that were fixed in first release of SpreadJS V10.

To view the release notes, see here: SpreadJS Release Notes

To download Spread V10, click here: Spread Downloads

SpreadJS

  • The column header will now print when it is set after data binding.
  • The EDATE function now has the same result in both IE and Chrome.
  • Copying values with quotes from SpreadJS and pasting into notepad no longer appends extra quotes.
  • DragFillUndoAction performance has been fixed.
  • HTML exporting no longer results in black backgrounds in some cells.
  • SpreadJS files save correctly in Google Drive now.
  • Copying and pasting text with double quotes from Excel no longer selects an extra row in the SpreadJS Designer.
  • Scrolling now works with filters.
  • Hyperlink with different fonts doesn’t show as strikethroughs in Firefox anymore.
  • Using multiple filters now shows hidden values as well.
  • Deleting rows after applying filters now works.
  • The Expression range no longer changes after adding/deleting a row.
  • Group Rendering and AddRow performance issues have been fixed.
  • SUM formula now evaluates correctly in Chrome.
  • autoFitColumn() with the AutoFitType set to CellWithHeader now works in Chrome.
  • The SheetNameChanged event works in Firefox now.
  • The browser doesn’t go into an infinite loop anymore when the value of a word wrapped cell is a space and its column width is set to be very small.
  • The DataValidation list does not change behavior when opening the XLSX file in SpreadJS.
  • There is no longer an error when using cross-sheet references in formulas.
  • There is no longer unexpected scrolling when setting a frozen row.
  • ExcelIO import issues have been fixed.
  • Setting the cell border now works when a default style is applied for the sheet.
  • A problem with the SpreadJS Designer Excel file open feature has been fixed.
  • The onRowChanged event now has a return-type and doesn’t throw a typescript compilation error.
  • Duplicate items in the FilterDropDown that use the same word no longer use a blank space.
  • Performance issues with floating objects have been fixed.
  • The DataValidation dropdown no longer gets stuck when hiding the Spread control.
  • An optional parameter has been added to removeTable() to allow the user to just remove table styles without removing the entire table.
  • Can now bind some columns in a table while also keeping data in other columns.
  • Certain formulas now work correctly.
  • The result of the EOMONTH formula is now in line with Excel.
  • Copying the buttonCellType now updates references so that changing the text of the new button does not affect the original one.
  • Users can now set tables without headers.
  • Print issues when setting spread.scrollbarMaxAlign(true) have been fixed.
  • Excel import issues have been fixed.
  • Setting borders for cells in Excel to none still shows borders when importing into SpreadJS.
  • Users can now edit sheet names when Spread is in a modal dialog.
  • AutoFitRow issues when zoom is less than 1 have been fixed.
  • Importing an XLS file with cross-sheet references no longer shows an error in the cell.
  • When multiple headers are copied and pasted into a span cell, there is no longer an error when undoing.
  • The startSheetIndex is now updated when the user adds a sheet.
  • When there are multiple row headers in a span, the celltype mouse event now fires when the second row is clicked.
  • Grouping performance issues have been fixed.
  • Hyperlink rendering in Firefox has been fixed.
  • Merge sort performance has been enhanced for the unbound use case.
  • Fixed the data validation drop-down not being hidden.
  • Fixed calculation bugs related to circular references.
  • Fixed an issue with the dynamic data validation list.
  • Copying and pasting text with a double quote from Excel no longer selects an extra row in the SpreadJS Designer.

Getting Started with SpreadJS V10

$
0
0

SpreadJS Version 10 now includes two JavaScript components: Spread.Sheets and Spread.Views. Spread.Sheets is a more traditional spreadsheet component, while Spread.Views is a highly customizable data view component. This tutorial shows how to get started with both components.

To download the sample pages used in this tutorial, see here: SpreadJS Getting Started Samples

Spread.Sheets

The Spread.Sheets component can be implemented in a web page with a small amount of code in a short amount of time. All you need is the core JavaScript library and style sheet, as there are no external dependencies.

In this tutorial, the hosted versions of the Spread.Sheets files are used to show how to implement an instance of the Spread.Sheets control in a web page. You can use the same links or download SpreadJS and use the files locally. Either way, the Spread.Sheets component should show up on the page.

Be sure to check out the Spread.Sheets Tutorial Site for over 100 more feature tutorials and examples.

To start off, add these references to the Spread.Sheets core JavaScript and CSS files to your HTML’s HEAD section:


<link href=" http://cdn.grapecity.com/spreadjs/hosted/css/gc.spread.sheets.excel2013white.10.0.0.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src=" http://cdn.grapecity.com/spreadjs/hosted/scripts/gc.spread.sheets.all.10.0.0.min.js"></script>

Then use the window.onload function to initialize the Spread.Sheets component and get the Spread object.


var spread = new GC.Spread.Sheets.Workbook(document.getElementById("ss"), { sheetCount: 1 });

In the HTML code, use a DIV and the object’s ID (in this example, “ss”) to place the sheet in the page’s BODY section.


<body>
      <div id='ss' style='width:100%; height:500px;'></div>
</body>

That’s all there is to getting started with using Spread.Sheets on a webpage. Now you can add some data as a table to the sheet:


var data = [{ "Id": 11074, "OrderDate": 42647, "RequiredDate": 35949, "ShipVia": 2, "Freight": 18.44, "ShipName": "Simons bistro", "ShipAddress": "Vinbæltet 34", "ShipCity": "Kobenhavn", "ShipPostalCode": "1734", "ShipCountry": "Denmark", "Employee": "Laura Callahan", "Customer": "Simons bistro", "ProductId": 16, "UnitPrice": 17.45, "Quantity": 14, "Discount": 0.05 },
{ "Id": 11075, "OrderDate": 42648, "RequiredDate": 35949, "ShipVia": 2, "Freight": 6.19, "ShipName": "Richter Supermarkt", "ShipAddress": "Starenweg 5", "ShipCity": "Genève", "ShipPostalCode": "1204", "ShipCountry": "Switzerland", "Employee": "Anne Dodsworth", "Customer": "Richter Supermarkt", "ProductId": 2, "UnitPrice": 19, "Quantity": 10, "Discount": 0.15 },
{ "Id": 11075, "OrderDate": 42649, "RequiredDate": 35949, "ShipVia": 2, "Freight": 6.19, "ShipName": "Richter Supermarkt", "ShipAddress": "Starenweg 5", "ShipCity": "Genève", "ShipPostalCode": "1204", "ShipCountry": "Switzerland", "Employee": "Anne Dodsworth", "Customer": "Richter Supermarkt", "ProductId": 46, "UnitPrice": 12, "Quantity": 30, "Discount": 0.15 },
{ "Id": 11075, "OrderDate": 42650, "RequiredDate": 35949, "ShipVia": 2, "Freight": 6.19, "ShipName": "Richter Supermarkt", "ShipAddress": "Starenweg 5", "ShipCity": "Genève", "ShipPostalCode": "1204", "ShipCountry": "Switzerland", "Employee": "Anne Dodsworth", "Customer": "Richter Supermarkt", "ProductId": 76, "UnitPrice": 18, "Quantity": 2, "Discount": 0.15 },
{ "Id": 11076, "OrderDate": 42651, "RequiredDate": 35949, "ShipVia": 2, "Freight": 38.28, "ShipName": "Bon app'", "ShipAddress": "12, rue des Bouchers", "ShipCity": "Marseille", "ShipPostalCode": "13008", "ShipCountry": "France", "Employee": "Steven Buchanan", "Customer": "Bon app", "ProductId": 6, "UnitPrice": 25, "Quantity": 20, "Discount": 0.25 },
{ "Id": 11076, "OrderDate": 42654, "RequiredDate": 35949, "ShipVia": 2, "Freight": 38.28, "ShipName": "Bon app'", "ShipAddress": "12, rue des Bouchers", "ShipCity": "Marseille", "ShipPostalCode": "13008", "ShipCountry": "France", "Employee": "Steven Buchanan", "Customer": "Bon app", "ProductId": 14, "UnitPrice": 23.25, "Quantity": 20, "Discount": 0.25 },
{ "Id": 11076, "OrderDate": 42656, "RequiredDate": 35949, "ShipVia": 2, "Freight": 38.28, "ShipName": "Bon app'", "ShipAddress": "12, rue des Bouchers", "ShipCity": "Marseille", "ShipPostalCode": "13008", "ShipCountry": "France", "Employee": "Steven Buchanan", "Customer": "Bon app", "ProductId": 19, "UnitPrice": 9.2, "Quantity": 10, "Discount": 0.25 },
{ "Id": 11077, "OrderDate": 42657, "RequiredDate": 35949, "ShipVia": 2, "Freight": 8.53, "ShipName": "Rattlesnake Canyon Grocery", "ShipAddress": "2817 Milton Dr.", "ShipCity": "Albuquerque", "ShipRegion": "NM", "ShipPostalCode": "87110", "ShipCountry": "USA", "Employee": "Andrew Fuller", "Customer": "Rattlesnake Canyon Grocery", "ProductId": 2, "UnitPrice": 19, "Quantity": 24, "Discount": 0.2 },
{ "Id": 11077, "OrderDate": 42658, "RequiredDate": 35949, "ShipVia": 2, "Freight": 8.53, "ShipName": "Rattlesnake Canyon Grocery", "ShipAddress": "2817 Milton Dr.", "ShipCity": "Albuquerque", "ShipRegion": "NM", "ShipPostalCode": "87110", "ShipCountry": "USA", "Employee": "Andrew Fuller", "Customer": "Rattlesnake Canyon Grocery", "ProductId": 3, "UnitPrice": 10, "Quantity": 4, "Discount": 0 },
{ "Id": 11077, "OrderDate": 42661, "RequiredDate": 35949, "ShipVia": 2, "Freight": 8.53, "ShipName": "Rattlesnake Canyon Grocery", "ShipAddress": "2817 Milton Dr.", "ShipCity": "Albuquerque", "ShipRegion": "NM", "ShipPostalCode": "87110", "ShipCountry": "USA", "Employee": "Andrew Fuller", "Customer": "Rattlesnake Canyon Grocery", "ProductId": 4, "UnitPrice": 22, "Quantity": 1, "Discount": 0 },
{ "Id": 11077, "OrderDate": 42662, "RequiredDate": 35949, "ShipVia": 2, "Freight": 8.53, "ShipName": "Rattlesnake Canyon Grocery", "ShipAddress": "2817 Milton Dr.", "ShipCity": "Albuquerque", "ShipRegion": "NM", "ShipPostalCode": "87110", "ShipCountry": "USA", "Employee": "Andrew Fuller", "Customer": "Rattlesnake Canyon Grocery", "ProductId": 13, "UnitPrice": 6, "Quantity": 4, "Discount": 0 },
{ "Id": 11077, "OrderDate": 42663, "RequiredDate": 35949, "ShipVia": 2, "Freight": 8.53, "ShipName": "Rattlesnake Canyon Grocery", "ShipAddress": "2817 Milton Dr.", "ShipCity": "Albuquerque", "ShipRegion": "NM", "ShipPostalCode": "87110", "ShipCountry": "USA", "Employee": "Andrew Fuller", "Customer": "Rattlesnake Canyon Grocery", "ProductId": 14, "UnitPrice": 23.25, "Quantity": 1, "Discount": 0.03 },
{ "Id": 11077, "OrderDate": 42765, "RequiredDate": 35949, "ShipVia": 2, "Freight": 8.53, "ShipName": "Rattlesnake Canyon Grocery", "ShipAddress": "2817 Milton Dr.", "ShipCity": "Albuquerque", "ShipRegion": "NM", "ShipPostalCode": "87110", "ShipCountry": "USA", "Employee": "Andrew Fuller", "Customer": "Rattlesnake Canyon Grocery", "ProductId": 16, "UnitPrice": 17.45, "Quantity": 2, "Discount": 0.03 },
{ "Id": 11038, "OrderDate": 42769, "RequiredDate": 35934, "ShippedDate": 35915, "ShipVia": 2, "Freight": 29.59, "ShipName": "Suprêmes délices", "ShipAddress": "Boulevard Tirou, 255", "ShipCity": "Charleroi", "ShipPostalCode": "B-6000", "ShipCountry": "Belgium", "Employee": "Andrew Fuller", "Customer": "Suprêmes délices", "ProductId": 40, "UnitPrice": 18.4, "Quantity": 5, "Discount": 0.2 },
{ "Id": 11038, "OrderDate": 42771, "RequiredDate": 35934, "ShippedDate": 35915, "ShipVia": 2, "Freight": 29.59, "ShipName": "Suprêmes délices", "ShipAddress": "Boulevard Tirou, 255", "ShipCity": "Charleroi", "ShipPostalCode": "B-6000", "ShipCountry": "Belgium", "Employee": "Andrew Fuller", "Customer": "Suprêmes délices", "ProductId": 52, "UnitPrice": 7, "Quantity": 2, "Discount": 0 },
{ "Id": 11038, "OrderDate": 42772, "RequiredDate": 35934, "ShippedDate": 35915, "ShipVia": 2, "Freight": 29.59, "ShipName": "Suprêmes délices", "ShipAddress": "Boulevard Tirou, 255", "ShipCity": "Charleroi", "ShipPostalCode": "B-6000", "ShipCountry": "Belgium", "Employee": "Andrew Fuller", "Customer": "Suprêmes délices", "ProductId": 71, "UnitPrice": 21.5, "Quantity": 30, "Discount": 0 }
];

Then add a table with data from that data source:


sheet.tables.addFromDataSource("Table1", 0, 0, data, GC.Spread.Sheets.Tables.TableThemes.dark7);

Don’t forget to visit the SpreadJS Tutorial Site to learn how to implement and customize features.

Spread.Sheets V10 Page

Spread.Sheets V10 Page

Spread.Views

In this part of the tutorial, we will use the same data that was used in the Spread.Sheets tutorial, to show how both components display the data differently. The Calendar View is a great example of the different kinds of data views that can be implemented easily with Spread.Views. Most of the code for this example comes from the Sales Report demo, with a few tweaks to suit our particular data.

Since the data in our sample is different from the Sales Report demo, we need to change the column definitions:


var columns = [{
    id: 'orderDate',
    caption: 'Order Date',
    dataField: 'OrderDate',
    format: 'yyyy/MM/dd'
}, {
    id: 'shipName',
    caption: 'Shipping Name',
    dataField: 'ShipName'
}, {
    id: 'shipAddress',
    caption: 'Shipping Address',
    dataField: 'ShipAddress'
}, {
    id: 'shipCity',
    caption: 'Shipping City',
    dataField: 'ShipCity'
}, {
    id: 'shipRegion',
    caption: 'Shipping Region',
    dataField: 'ShipRegion'
}, {
    id: 'shipCountry',
    caption: 'Shipping Country',
    dataField: 'ShipCountry'
}, {
    id: 'productId',
    caption: 'Product ID',
    dataField: 'ProductId'
}, {
    id: 'unitPrice',
    caption: 'Unit Price',
    dataField: 'UnitPrice',
    format: '$#,##0'
}, {
    id: 'quantity',
    caption: 'Quantity',
    dataField: 'Quantity'
}, {
    id: 'sales',
    dataField: '=[quantity]*[unitPrice]',
    format: '$#,##0'
}];

Then we can change the header template (which is used for the actual days in the calendar) and the row template (which is used for the “details” dialog):


var headerTemplate = '<div class="summaryCell">' +
    '<div class="salesContainer"><span>summary</span><div class="sales">${{=it.eval("=sum([sales])", "#,##")}}</div></div>' +
    '</div>';

var rowTemplate = '<div>' +
    '<div class="orderPropertyName">Name:</div><div class="orderProperty">{{=it.shipName}}</div>' +
    '<div></div>' +
    '<div class="orderPropertyName">Product ID:</div><div class="orderProperty">{{=it.productId}}</div>' +
    '<div></div>' +
    '<div class="orderPropertyName">Shipping Address:</div><div class="orderProperty">{{=it.shipAddress}}, {{=it.shipCity}}, {{=it.shipCountry}}</div>' +
    '<div></div>' +
    '<div class="orderPropertyName">Unit Price:</div><div class="orderProperty">{{=it.unitPrice}}</div>' +
    '<div></div>' +
    '<div class="orderPropertyName">Quantity:</div><div class="orderProperty">{{=it.quantity}}</div>' +
    '<div></div>' +
    '<div class="orderPropertyName">Sales:</div><div class="orderProperty">{{=it.sales}}</div>' +
    '<div></div>' +
    '</div>';

That’s all there is to implementing your own Calendar View with Spread.Views. A few changes to the demo results in a calendar that suits our data, with very little code that needs to be rewritten. This tutorial shows how easy it is to work with Spread.Sheets and Spread.Views. With a small amount of code, you can add a spreadsheet and data view component to your page. To see the Spread.Views Demos, make sure to check out this link: Spread.Views Demos

Spread.Views V10 Page

Spread.Views V10 Page

Spread Studio V10 Fixed Bugs

$
0
0

In this article, you will find all of the .NET bugs that were fixed in the first release of Spread Studio V10.

To view the release notes, see here: Version 10 Release Notes

To download Spread Studio V10, click here: Spread V10 Downloads

Spread for WinForms

  • Missing borders fixed when overflow text is too long.
  • Right-aligned text now overflows to adjacent cells.
  • SetColumnVisible now works in specific situations.
  • Ctrl-X no longer changes the formula reference style.
  • Selecting the corner of the sheet and copying no longer hangs the application.
  • Opening an Excel file from a stream with conditional formatting with formulas no longer throws an exception.
  • Memory usage no longer increases when searching in Spread.
  • TextTipPolicy no longer shows TextTips on Sheet tabs.
  • QR Code no longer disappears after clicking on any cell.
  • Print preview no longer produces an empty page when the frozen column size is greater than the page size.
  • DragFillDataOnly and AllowUndo now work together correctly.
  • INDEX formula now works correctly.
  • Issue with attaching an FpSpread instance to the NameBox control more than once is fixed.
  • The height of the NameBox control can now be resized.
  • The space character is no longer cleared when setting GcDateTimeCellType.PromptChar to a space in the Spread Designer.
  • PrintInfo with Header and Footer format is now fixed after Excel export.
  • The Horizontal and Vertical Scroll tooltip now appears close to the scroll bars.
  • Null reference exception fixed when showing another form during the formulaChanged event.

Spread for ASP.NET

  • Client performance in Internet Explorer 11 has been enhanced.
  • A problem with scrolling in Chrome with Frozen Rows/Columns has been fixed.
  • An issue with Spread working with C1 Tab has been fixed.
  • An issue with XML Serialization from previous versions of Spread has been fixed.

Spread Windows Forms and the Funnel Chart

$
0
0

Funnel charts can be a useful tool in your application. For example, since Funnel charts show values across multiple stages, they can be used to find out how many sales leads convert to purchases.

Spread for Windows Forms 10 now supports the Funnel chart. Creating a Funnel chart in Spread Win is simple.

The following steps show how to create a Funnel chart.

  1. Create a series and add data and category names.
    FarPoint.Win.Chart.FunnelSeries funnel = new FarPoint.Win.Chart.FunnelSeries();
    funnel.Values.Add(200);
    funnel.Values.Add(180);
    funnel.Values.Add(50);
    funnel.Values.Add(30);
    funnel.Values.Add(8);
    funnel.CategoryNames.Add("Leads");
    funnel.CategoryNames.Add("Emails Sent");
    funnel.CategoryNames.Add("Replies");
    funnel.CategoryNames.Add("Quotes");
    funnel.CategoryNames.Add("Purchases");
  2. Add any formatting.
    funnel.BarFills.AddRange(new FarPoint.Win.Chart.GradientFill[] { new FarPoint.Win.Chart.GradientFill(Color.LightGreen, Color.Yellow), new FarPoint.Win.Chart.GradientFill(Color.LightBlue, Color.Thistle), new FarPoint.Win.Chart.GradientFill(Color.LightGray, Color.LightPink), new FarPoint.Win.Chart.GradientFill(Color.Beige, Color.Orange), new FarPoint.Win.Chart.GradientFill(Color.LightSalmon, Color.RosyBrown) });
    funnel.BarBorders.AddRange(new FarPoint.Win.Chart.Line[] { new FarPoint.Win.Chart.SolidLine(Color.DarkOliveGreen), new FarPoint.Win.Chart.SolidLine(Color.DarkBlue), new FarPoint.Win.Chart.SolidLine(Color.Black), new FarPoint.Win.Chart.SolidLine(Color.DarkOrange), new FarPoint.Win.Chart.SolidLine(Color.Firebrick) });
  3. Create the plot area and add the series to the plot area.
    FarPoint.Win.Chart.YPlotArea plotArea = new FarPoint.Win.Chart.YPlotArea();
    plotArea.Location = new PointF(0.2f, 0.2f);
    plotArea.Size = new SizeF(0.6f, 0.6f);
    plotArea.Series.Add(funnel);
  4. Create a chart model and add the plot area to the chart model.
    FarPoint.Win.Chart.ChartModel model = new FarPoint.Win.Chart.ChartModel();
    model.PlotAreas.Add(plotArea);
  5. Create a chart object and add the model and set any size or position properties.
    FarPoint.Win.Spread.Chart.SpreadChart chart = new FarPoint.Win.Spread.Chart.SpreadChart();
    chart.Model = model;
    chart.Left = 0;
    chart.Top = 150;
    chart.Size = new Size(600, 400);
  6. Add the chart.
    fpSpread1.ActiveSheet.Charts.Add(chart);
winfunnelblog

Funnel Chart

The following is the complete code sample in C#:

FarPoint.Win.Chart.FunnelSeries funnel = new FarPoint.Win.Chart.FunnelSeries();
funnel.Values.Add(200);
funnel.Values.Add(180);
funnel.Values.Add(50);
funnel.Values.Add(30);
funnel.Values.Add(8);
funnel.CategoryNames.Add("Leads");
funnel.CategoryNames.Add("Emails Sent");
funnel.CategoryNames.Add("Replies");
funnel.CategoryNames.Add("Quotes");
funnel.CategoryNames.Add("Purchases");
funnel.BarFills.AddRange(new FarPoint.Win.Chart.GradientFill[] { new FarPoint.Win.Chart.GradientFill(Color.LightGreen, Color.Yellow), new FarPoint.Win.Chart.GradientFill(Color.LightBlue, Color.Thistle), new FarPoint.Win.Chart.GradientFill(Color.LightGray, Color.LightPink), new FarPoint.Win.Chart.GradientFill(Color.Beige, Color.Orange), new FarPoint.Win.Chart.GradientFill(Color.LightSalmon, Color.RosyBrown) });
funnel.BarBorders.AddRange(new FarPoint.Win.Chart.Line[] { new FarPoint.Win.Chart.SolidLine(Color.DarkOliveGreen), new FarPoint.Win.Chart.SolidLine(Color.DarkBlue), new FarPoint.Win.Chart.SolidLine(Color.Black), new FarPoint.Win.Chart.SolidLine(Color.DarkOrange), new FarPoint.Win.Chart.SolidLine(Color.Firebrick) });
FarPoint.Win.Chart.YPlotArea plotArea = new FarPoint.Win.Chart.YPlotArea();
plotArea.Location = new PointF(0.2f, 0.2f);
plotArea.Size = new SizeF(0.6f, 0.6f);
plotArea.Series.Add(funnel);
FarPoint.Win.Chart.ChartModel model = new FarPoint.Win.Chart.ChartModel();
model.PlotAreas.Add(plotArea);
FarPoint.Win.Spread.Chart.SpreadChart chart = new FarPoint.Win.Spread.Chart.SpreadChart();
chart.Model = model;
chart.Left = 0;
chart.Top = 150;
chart.Size = new Size(600, 400);
fpSpread1.ActiveSheet.Charts.Add(chart);
fpSpread1.Font = new System.Drawing.Font("Calibri", 11);

The following is the complete code sample in VB:

Dim funnel As New FarPoint.Win.Chart.FunnelSeries()
funnel.Values.Add(200)
funnel.Values.Add(180)
funnel.Values.Add(50)
funnel.Values.Add(30)
funnel.Values.Add(8)
funnel.CategoryNames.Add("Leads")
funnel.CategoryNames.Add("Emails Sent")
funnel.CategoryNames.Add("Replies")
funnel.CategoryNames.Add("Quotes")
funnel.CategoryNames.Add("Purchases")
funnel.BarFills.AddRange(New FarPoint.Win.Chart.GradientFill() {New FarPoint.Win.Chart.GradientFill(Color.LightGreen, Color.Yellow), New FarPoint.Win.Chart.GradientFill(Color.LightBlue, Color.Thistle), New FarPoint.Win.Chart.GradientFill(Color.LightGray, Color.LightPink), New FarPoint.Win.Chart.GradientFill(Color.Beige, Color.Orange), New FarPoint.Win.Chart.GradientFill(Color.LightSalmon, Color.RosyBrown)})
funnel.BarBorders.AddRange(New FarPoint.Win.Chart.Line() {New FarPoint.Win.Chart.SolidLine(Color.DarkOliveGreen), New FarPoint.Win.Chart.SolidLine(Color.DarkBlue), New FarPoint.Win.Chart.SolidLine(Color.Black), New FarPoint.Win.Chart.SolidLine(Color.DarkOrange), New FarPoint.Win.Chart.SolidLine(Color.Firebrick)})
Dim plotArea As New FarPoint.Win.Chart.YPlotArea()
plotArea.Location = New PointF(0.2F, 0.2F)
plotArea.Size = New SizeF(0.6F, 0.6F)
plotArea.Series.Add(funnel)
Dim model As New FarPoint.Win.Chart.ChartModel()
model.PlotAreas.Add(plotArea)
Dim chart As New FarPoint.Win.Spread.Chart.SpreadChart()
chart.Model = model
chart.Left = 0
chart.Top = 150
chart.Size = New Size(600, 400)
FpSpread1.ActiveSheet.Charts.Add(chart)
FpSpread1.Font = New System.Drawing.Font("Calibri", 11)

You can also add charts in the Spread Designer. Simply add the data to the designer, select the data, and then select the chart type (Insert, Create Chart dialog, and Funnel).

winfunneldesign1

Add Data

winfunneldesign2

Select Data and Chart Type

winfunneldesign3

Funnel Chart

Spread Windows Forms and the Sunburst Chart

$
0
0

Sunburst charts are effective for showing hierarchical data visually. For example, you can use a Sunburst chart to find out what store and product have the most sales.

Spread for Windows Forms and Spread for ASP.NET 10 now have the Sunburst chart.

The following image displays a Sunburst chart. You can quickly spot the store with the most sales and the best-selling products.

WinSunburst

Sunburst Chart

Use the following steps to create a Sunburst chart.

  1. Create a Sunburst series.
    FarPoint.Win.Chart.SunburstSeries series = new FarPoint.Win.Chart.SunburstSeries();
  2. Add data.
    series.Values.AddRange(new double[] { 350, 100, 80, 85, 90, 200, 350, 450, 500, 650, 220 });
  3. Set any colors.
    series.Fills.AddRange(new FarPoint.Win.Chart.Fill[] { new FarPoint.Win.Chart.SolidFill(Color.Blue), new FarPoint.Win.Chart.SolidFill(Color.Teal), new FarPoint.Win.Chart.SolidFill(Color.DarkGoldenrod), new
    FarPoint.Win.Chart.SolidFill(Color.DarkSalmon), new FarPoint.Win.Chart.SolidFill(Color.DarkGreen), new FarPoint.Win.Chart.SolidFill(Color.Chocolate), new FarPoint.Win.Chart.SolidFill(Color.Navy), new
    FarPoint.Win.Chart.SolidFill(Color.DarkOrange), new FarPoint.Win.Chart.SolidFill(Color.OrangeRed), new FarPoint.Win.Chart.SolidFill(Color.Tomato), new FarPoint.Win.Chart.SolidFill(Color.Firebrick), new
    FarPoint.Win.Chart.SolidFill(Color.Gray), new FarPoint.Win.Chart.SolidFill(Color.Olive), new FarPoint.Win.Chart.SolidFill(Color.Teal) });
  4. Add text strings for the data.
    FarPoint.Win.Chart.StringCollectionItem collection1 = new FarPoint.Win.Chart.StringCollectionItem();
    collection1.AddRange(new String[] { "Store 1", "", "", "", "", "", "Store 2", "", "", "Store 3" });
    FarPoint.Win.Chart.StringCollectionItem collection2 = new FarPoint.Win.Chart.StringCollectionItem();
    collection2.AddRange(new String[] { "Asagio", "Swiss", "Muenster", "Blue", "Cabot", "Gouda", "Feta", "Brie", "Stilton", "American", "Asagio" });
    FarPoint.Win.Chart.StringCollectionItem collection3 = new FarPoint.Win.Chart.StringCollectionItem();
    collection3.AddRange(new String[] { "", "", "", "", "", "", "", "", "", "", "Week1" });
    series.CategoryNames.AddRange(new FarPoint.Win.Chart.StringCollectionItem[] { collection1, collection2, collection3 });
  5. Add any legends or labels.
    FarPoint.Win.Chart.LegendArea label = new FarPoint.Win.Chart.LegendArea();
    label.TextFont = new System.Drawing.Font("Calibri", 10);
    label.TextFill = new FarPoint.Win.Chart.SolidFill(System.Drawing.Color.Black);
  6. Create a plot area and add the series to the plot area.
    FarPoint.Win.Chart.SunburstPlotArea plotArea = new FarPoint.Win.Chart.SunburstPlotArea();
    plotArea.Location = new PointF(0.2f, 0.2f);
    plotArea.Size = new SizeF(0.6f, 0.6f);
    plotArea.Series.Add(series);
  7. Create a chart model and add the plot area and legend.
    FarPoint.Win.Chart.ChartModel model = new FarPoint.Win.Chart.ChartModel();
    model.PlotAreas.Add(plotArea);
    model.LegendAreas.Add(label);
  8. Create a chart object, set the size and location, and assign the model.
    FarPoint.Win.Spread.Chart.SpreadChart chart = new FarPoint.Win.Spread.Chart.SpreadChart();
    chart.Size = new Size(600, 700);
    chart.Location = new System.Drawing.Point(50, 50);
    chart.Model = model;
  9. Add the chart to Spread.
    fpSpread1.Sheets[0].Charts.Add(chart);

Here is the complete Spread for Windows Forms C# code:

FarPoint.Win.Chart.SunburstSeries series = new FarPoint.Win.Chart.SunburstSeries();
series.Values.AddRange(new double[] { 350, 100, 80, 85, 90, 200, 350, 450, 500, 650, 220 });
series.Fills.AddRange(new FarPoint.Win.Chart.Fill[] { new FarPoint.Win.Chart.SolidFill(Color.Blue), new FarPoint.Win.Chart.SolidFill(Color.Teal), new FarPoint.Win.Chart.SolidFill(Color.DarkGoldenrod), new
FarPoint.Win.Chart.SolidFill(Color.DarkSalmon), new FarPoint.Win.Chart.SolidFill(Color.DarkGreen), new FarPoint.Win.Chart.SolidFill(Color.Chocolate), new FarPoint.Win.Chart.SolidFill(Color.Navy), new
FarPoint.Win.Chart.SolidFill(Color.DarkOrange), new FarPoint.Win.Chart.SolidFill(Color.OrangeRed), new FarPoint.Win.Chart.SolidFill(Color.Tomato), new FarPoint.Win.Chart.SolidFill(Color.Firebrick), new
FarPoint.Win.Chart.SolidFill(Color.Gray), new FarPoint.Win.Chart.SolidFill(Color.Olive), new FarPoint.Win.Chart.SolidFill(Color.Teal) });
FarPoint.Win.Chart.StringCollectionItem collection1 = new FarPoint.Win.Chart.StringCollectionItem();
collection1.AddRange(new String[] { "Store 1", "", "", "", "", "", "Store 2", "", "", "Store 3" });
FarPoint.Win.Chart.StringCollectionItem collection2 = new FarPoint.Win.Chart.StringCollectionItem();
collection2.AddRange(new String[] { "Asagio", "Swiss", "Muenster", "Blue", "Cabot", "Gouda", "Feta", "Brie", "Stilton", "American", "Asagio" });
FarPoint.Win.Chart.StringCollectionItem collection3 = new FarPoint.Win.Chart.StringCollectionItem();
collection3.AddRange(new String[] { "", "", "", "", "", "", "", "", "", "", "Week1" });
series.CategoryNames.AddRange(new FarPoint.Win.Chart.StringCollectionItem[] { collection1, collection2, collection3 });
FarPoint.Win.Chart.LegendArea label = new FarPoint.Win.Chart.LegendArea();
label.TextFont = new System.Drawing.Font("Calibri", 10);
label.TextFill = new FarPoint.Win.Chart.SolidFill(System.Drawing.Color.Black);
FarPoint.Win.Chart.SunburstPlotArea plotArea = new FarPoint.Win.Chart.SunburstPlotArea();
plotArea.Location = new PointF(0.2f, 0.2f);
plotArea.Size = new SizeF(0.6f, 0.6f);
plotArea.Series.Add(series);
FarPoint.Win.Chart.ChartModel model = new FarPoint.Win.Chart.ChartModel();
model.PlotAreas.Add(plotArea);
model.LegendAreas.Add(label);
FarPoint.Win.Spread.Chart.SpreadChart chart = new FarPoint.Win.Spread.Chart.SpreadChart();
chart.Size = new Size(600, 700);
chart.Location = new System.Drawing.Point(50, 50);
chart.Model = model;
fpSpread1.Sheets[0].Charts.Add(chart);

Here is the complete Spread for Windows Forms VB code:

Dim series As New FarPoint.Win.Chart.SunburstSeries()
series.Values.AddRange(New Double() {350, 100, 80, 85, 90, 200, 350, 450, 500, 650, 220})
series.Fills.AddRange(New FarPoint.Win.Chart.Fill() {New FarPoint.Win.Chart.SolidFill(Color.Blue), New FarPoint.Win.Chart.SolidFill(Color.Teal), New FarPoint.Win.Chart.SolidFill(Color.DarkGoldenrod), New FarPoint.Win.Chart.SolidFill(Color.DarkSalmon), New FarPoint.Win.Chart.SolidFill(Color.DarkGreen), New FarPoint.Win.Chart.SolidFill(Color.Chocolate), New FarPoint.Win.Chart.SolidFill(Color.Navy), New FarPoint.Win.Chart.SolidFill(Color.DarkOrange), New FarPoint.Win.Chart.SolidFill(Color.OrangeRed), New FarPoint.Win.Chart.SolidFill(Color.Tomato), New FarPoint.Win.Chart.SolidFill(Color.Firebrick), New FarPoint.Win.Chart.SolidFill(Color.Gray), New FarPoint.Win.Chart.SolidFill(Color.Olive), New FarPoint.Win.Chart.SolidFill(Color.Teal)})
Dim collection1 As New FarPoint.Win.Chart.StringCollectionItem()
collection1.AddRange(New String() {"Store 1", "", "", "", "", "", "Store 2", "", "", "Store 3"})
Dim collection2 As New FarPoint.Win.Chart.StringCollectionItem()
collection2.AddRange(New String() {"Asagio", "Swiss", "Muenster", "Blue", "Cabot", "Gouda", "Feta", "Brie", "Stilton", "American", "Asagio"})
Dim collection3 As New FarPoint.Win.Chart.StringCollectionItem()
collection3.AddRange(New String() {"", "", "", "", "", "", "", "", "", "", "Week1"})
series.CategoryNames.AddRange(New FarPoint.Win.Chart.StringCollectionItem() {collection1, collection2, collection3})
Dim Label As New FarPoint.Win.Chart.LegendArea()
Label.TextFont = New System.Drawing.Font("Calibri", 10)
Label.TextFill = New FarPoint.Win.Chart.SolidFill(System.Drawing.Color.Black)
Dim plotArea As New FarPoint.Win.Chart.SunburstPlotArea()
plotArea.Location = New PointF(0.2F, 0.2F)
plotArea.Size = New SizeF(0.6F, 0.6F)
plotArea.Series.Add(series)
Dim model As New FarPoint.Win.Chart.ChartModel()
model.PlotAreas.Add(plotArea)
model.LegendAreas.Add(Label)
Dim chart As New FarPoint.Win.Spread.Chart.SpreadChart()
chart.Size = New Size(600, 700)
chart.Location = New System.Drawing.Point(50, 50)
chart.Model = model
FpSpread1.Sheets(0).Charts.Add(chart)

Here is the complete Spread for ASP.NET C# code:

FarPoint.Web.Chart.SunburstSeries series = new FarPoint.Web.Chart.SunburstSeries();
series.Values.AddRange(new double[] { 350, 100, 80, 85, 90, 200, 350, 450, 500, 650, 220 });
series.Fills.AddRange(new FarPoint.Web.Chart.Fill[] { new FarPoint.Web.Chart.SolidFill(Color.Blue), new FarPoint.Web.Chart.SolidFill(Color.Teal), new FarPoint.Web.Chart.SolidFill(Color.DarkGoldenrod), new
FarPoint.Web.Chart.SolidFill(Color.DarkSalmon), new FarPoint.Web.Chart.SolidFill(Color.DarkGreen), new FarPoint.Web.Chart.SolidFill(Color.Chocolate), new FarPoint.Web.Chart.SolidFill(Color.Navy), new
FarPoint.Web.Chart.SolidFill(Color.DarkOrange), new FarPoint.Web.Chart.SolidFill(Color.OrangeRed), new FarPoint.Web.Chart.SolidFill(Color.Tomato), new FarPoint.Web.Chart.SolidFill(Color.Firebrick), new
FarPoint.Web.Chart.SolidFill(Color.Gray), new FarPoint.Web.Chart.SolidFill(Color.Olive), new FarPoint.Web.Chart.SolidFill(Color.Teal) });
FarPoint.Web.Chart.StringCollectionItem collection1 = new FarPoint.Web.Chart.StringCollectionItem();
collection1.AddRange(new String[] { "Store 1", "", "", "", "", "", "Store 2", "", "", "Store 3" });
FarPoint.Web.Chart.StringCollectionItem collection2 = new FarPoint.Web.Chart.StringCollectionItem();
collection2.AddRange(new String[] { "Asagio", "Swiss", "Muenster", "Blue", "Cabot", "Gouda", "Feta", "Brie", "Stilton", "American", "Asagio" });
FarPoint.Web.Chart.StringCollectionItem collection3 = new FarPoint.Web.Chart.StringCollectionItem();
collection3.AddRange(new String[] { "", "", "", "", "", "", "", "", "", "", "Week1" });
series.CategoryNames.AddRange(new FarPoint.Web.Chart.StringCollectionItem[] { collection1, collection2, collection3 });
FarPoint.Web.Chart.LegendArea label = new FarPoint.Web.Chart.LegendArea();
label.TextFont = new System.Drawing.Font("Calibri", 10);
label.TextFill = new FarPoint.Web.Chart.SolidFill(System.Drawing.Color.Black);
FarPoint.Web.Chart.SunburstPlotArea plotArea = new FarPoint.Web.Chart.SunburstPlotArea();
plotArea.Location = new PointF(0.2f, 0.2f);
plotArea.Size = new SizeF(0.6f, 0.6f);
plotArea.Series.Add(series);
FarPoint.Web.Chart.ChartModel model = new FarPoint.Web.Chart.ChartModel();
model.PlotAreas.Add(plotArea);
model.LegendAreas.Add(label);
FarPoint.Web.Spread.Chart.SpreadChart chart = new FarPoint.Web.Spread.Chart.SpreadChart();
chart.Width = 600;
chart.Height = 700;
chart.Model = model;
FpSpread1.Sheets[0].Charts.Add(chart);

Here is the complete Spread for ASP.NET VB code:

Dim series As New FarPoint.Web.Chart.SunburstSeries()
series.Values.AddRange(New Double() {350, 100, 80, 85, 90, 200, 350, 450, 500, 650, 220})
series.Fills.AddRange(New FarPoint.Web.Chart.Fill() {New FarPoint.Web.Chart.SolidFill(Color.Blue), New FarPoint.Web.Chart.SolidFill(Color.Teal), New FarPoint.Web.Chart.SolidFill(Color.DarkGoldenrod), New FarPoint.Web.Chart.SolidFill(Color.DarkSalmon), New FarPoint.Web.Chart.SolidFill(Color.DarkGreen), New FarPoint.Web.Chart.SolidFill(Color.Chocolate), New FarPoint.Web.Chart.SolidFill(Color.Navy), New FarPoint.Web.Chart.SolidFill(Color.DarkOrange), New FarPoint.Web.Chart.SolidFill(Color.OrangeRed), New FarPoint.Web.Chart.SolidFill(Color.Tomato), New FarPoint.Web.Chart.SolidFill(Color.Firebrick), New FarPoint.Web.Chart.SolidFill(Color.Gray), New FarPoint.Web.Chart.SolidFill(Color.Olive), New FarPoint.Web.Chart.SolidFill(Color.Teal)})
Dim collection1 As New FarPoint.Web.Chart.StringCollectionItem()
collection1.AddRange(New String() {"Store 1", "", "", "", "", "", "Store 2", "", "", "Store 3"})
Dim collection2 As New FarPoint.Web.Chart.StringCollectionItem()
collection2.AddRange(New String() {"Asagio", "Swiss", "Muenster", "Blue", "Cabot", "Gouda", "Feta", "Brie", "Stilton", "American", "Asagio"})
Dim collection3 As New FarPoint.Web.Chart.StringCollectionItem()
collection3.AddRange(New String() {"", "", "", "", "", "", "", "", "", "", "Week1"})
series.CategoryNames.AddRange(New FarPoint.Web.Chart.StringCollectionItem() {collection1, collection2, collection3})
Dim Label As New FarPoint.Web.Chart.LegendArea()
Label.TextFont = New System.Drawing.Font("Calibri", 10)
Label.TextFill = New FarPoint.Web.Chart.SolidFill(System.Drawing.Color.Black)
Dim plotArea As New FarPoint.Web.Chart.SunburstPlotArea()
plotArea.Location = New PointF(0.2F, 0.2F)
plotArea.Size = New SizeF(0.6F, 0.6F)
plotArea.Series.Add(series)
Dim model As New FarPoint.Web.Chart.ChartModel()
model.PlotAreas.Add(plotArea)
model.LegendAreas.Add(Label)
Dim chart As New FarPoint.Web.Spread.Chart.SpreadChart()
chart.Width = 600
chart.Height = 700
chart.Model = model
FpSpread1.Sheets(0).Charts.Add(chart)

You can also add charts in the Spread Designer. Simply add the data to the designer, select the data, and then select the chart type (Insert, Create Chart dialog, and Sunburst).

winsundesign1

Add and Select Data

winsundesign2

Insert Sunburst Chart

winsundesign3

Sunburst Chart

Spread.Sheets V10 Cell Dependencies

$
0
0

In some cases, large spreadsheets have formulas with a lot of dependencies on other cells. Showing these dependencies can be useful. In Excel, there are keyboard shortcuts specifically for navigating to and selecting the dependent (and precedent) cells of the currently selected cell. These shortcuts are not currently in Spread.Sheets, but you can write code to add them. In this blog, you will learn how to add commands for shortcut keys to Spread.Sheets, as well as how to get dependent/precedent cells.

The download for this sample can be found here: Spread.Sheets V10 Dependencies

The finished page showing dependencies of a cell.

The finished page showing dependencies of a cell.

Set Up the Project

Create a simple HTML webpage and add references to the Spread.Sheets JS and CSS files:


<!DOCTYPE html>
<html>
<head>
    <title>SpreadJS - Samples</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <script src="http://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script>
    <link type="text/css" href="http://cdn.grapecity.com/spreadjs/hosted/css/gc.spread.sheets.excel2013white.10.0.0.css" rel="stylesheet" />
    <script type="text/javascript" src="http://cdn.grapecity.com/spreadjs/hosted/scripts/gc.spread.sheets.all.10.0.0.min.js"></script>

</head>
<body>
</body>
</html>

Add a DOM element and some initialization code for the Spread.Sheets instance:


    <script type="text/javascript">

       // GC.Spread.Sheets.LicenseKey = "";
        function init() {
            var spread = new GC.Spread.Sheets.Workbook(document.getElementById("ss"));
            var sheet = window.sheet = spread.getActiveSheet();

            sheet.setValue(0, 0, 2);
            sheet.setValue(0, 1, 3);
            sheet.setFormula(0, 2, "sum(A1:a2)+B1");
            sheet.setFormula(1, 2, "C1*2");
            sheet.setActiveCell(0, 2);
            
        }
    </script>
<body onload="init()">
</body>
The Spread.Sheets V10 instance on an HTML page.

The Spread.Sheets V10 instance on an HTML page.

Cell Dependencies

Now we have to write code to actually get the dependencies of a cell. This should return an array of those dependencies:


// Get the dependent cells of the cell at the specified row and column
function getDependencies(row, col) {
    var dependencies = [];
    var calcService = sheet.getCalcService();
    var sourceModels = calcService.getAllSouceModels();
    var sheetSourceModel = sourceModels[0];
    var expression = sheetSourceModel.getExpression(row, col);
    var node = sheetSourceModel.getNode(row, col);
    if (node) {
        let calcNode = node.calc;
        if (calcNode) {
            var cellListens = calcNode.cellListeners;
            for (var i = 0; cellListens && i < cellListens.length; i++) {
                var cellListen = cellListens[i];
                dependencies.push({ row: cellListen.row, col: cellListen.column });
            }
        }
    }
    return dependencies;
}

In addition, we have to write code for getting the precedent cells as well:


function getPrecedents(formula, row, column) {
    var expr = GC.Spread.Sheets.CalcEngine.formulaToExpression(sheet, formula, row, column);
    var pres = [];
    getPres(sheet, expr, pres, row, column);
    return pres;
}
// Get the precedent cells of the cell at the specified row and column
function getPres(sheet, expr, pres, row, column) {
    if (!expr) {
        return;
    }
    var ExpressionType = GC.Spread.CalcEngine.ExpressionType;
    while (expr.type === ExpressionType.parentheses) {
        expr = expr.value;
    }
    if (expr.type === ExpressionType.reference) {
        pres.push(expr.getRange(row, column));
    } else if (expr.type === ExpressionType.operator) {
        getPres(sheet, expr.value, pres, row, column);
        getPres(sheet, expr.value2, pres, row, column);
    } else if (expr.type === ExpressionType.function) {
        for (var i = 0; i < expr.arguments.length; i++) {
            getPres(sheet, expr.arguments[i], pres, row, column);
        }
    } else if (expr.type === ExpressionType.name) {
        var nameInfo = sheet.getCustomName(expr.value);
        if (nameInfo) {
            nameInfo = sheet.parent && sheet.parent.getCustomName && sheet.parent.getCustomName(expr.value);
        }
        if (nameInfo) {
            getPres(sheet, nameInfo.getExpression(), pres, row, column);
        }
    }
}

It might also be useful to display these dependencies in a text area on the page, so you can write additional functions to call the functions we just wrote:


function displayDependencies() {
    var row = sheet.getActiveRowIndex();
    var col = sheet.getActiveColumnIndex();
    var deps = getDependencies(row, col);
    var msg = "Dependencies:\r\n";
    for (var i = 0; i < deps.length; i++) {
        var range = deps[i];
        msg += range.row + ", " + range.col;
    }
    $("#msg").val(msg);
}
function displayPrecedents() {
    var pres = []
    var row = sheet.getActiveRowIndex();
    var column = sheet.getActiveColumnIndex();
    var formula = sheet.getFormula(row, column);
    if (!formula) {
        return;
    }
    var pres = getPrecedents(formula, row, column);
    var msg = "Precedents:\r\n";
    for (var i = 0; i < pres.length; i++) {
        var range = pres[i];
        for (var row = 0; row < range.rowCount; row++) {
            for (var col = 0; col < range.colCount; col++) {
                msg += (range.row + row) + ", " + (range.col + col) + "\r\n";
            }
        }
    }
    $("#msg").val(msg);
}

Add Commands

In order to make those functions fire with specific key actions, we have to first register them as commands in the Command Manager:


// Add commands to Spread.Sheets for selecting the precedents/dependents of a cell
function registerCommands(spread) {
    spread.commandManager().register('highlightPrecedents',
        function PrecedentAction() {
            var row = sheet.getActiveRowIndex();
            var column = sheet.getActiveColumnIndex();
            var formula = sheet.getFormula(row, column);
            if (!formula) {
                alert("No precedents!");
                return;
            }
            var precedents = getPrecedents(formula, row, column);
            spread.getActiveSheet().selectionPolicy(GC.Spread.Sheets.SelectionPolicy.multiRange);
            for (var i = 0; i < precedents.length; i++) {
                var range = precedents[i];
                if (i == 0) {
                    spread.getActiveSheet().setActiveCell(range.row, range.col);
                    spread.getActiveSheet().setSelection(range.row, range.col, range.rowCount, range.colCount);
                } else {
                    spread.getActiveSheet().addSelection(range.row, range.col, range.rowCount, range.colCount);
                }
            }
            return;
        }
    );
    spread.commandManager().register('highlightDependents',
        function DependentAction() {
            var row = sheet.getActiveRowIndex();
            var column = sheet.getActiveColumnIndex();
            var dependents = getDependencies(row, column);
            spread.getActiveSheet().selectionPolicy(GC.Spread.Sheets.SelectionPolicy.multiRange);
            for (var i = 0; i < dependents.length; i++) {
                var range = dependents[i];
                if (i == 0) {
                    spread.getActiveSheet().setActiveCell(range.row, range.col);
                    spread.getActiveSheet().setSelection(range.row, range.col, 1, 1);
                } else {
                    spread.getActiveSheet().addSelection(range.row, range.col, 1, 1);
                }
            }
            return;
        }
    );
}

After implementing the commands, we can connect those commands to the “Ctrl+[“ and “Ctrl+]” key shortcuts:


// Connect the commands for selecting depedent/precedent cells to the Ctrl+[ and Ctrl+] key combinations
function setShortcuts(spread) {
    spread.commandManager().setShortcutKey('highlightDependents', 221, true, false, false, false);
    spread.commandManager().setShortcutKey('highlightPrecedents', 219, true, false, false, false);
}

Lastly, add buttons and a text area on the page to correspond to the functions we added:


<input type="button" value="Get Precedents" onclick="displayPrecedents()"/>
<input type="button" value="Get Dependencies" onclick="displayDependencies()" />
<textarea id="msg" style="height:200px"></textarea>
The HTML page with the added textarea and buttons.

The HTML page with the added textarea and buttons.

When running the page, the user will be able to select cells and use “Ctrl+[“ and “Ctrl+]” to navigate to and select dependent and precedent cells of the current selection. The added buttons on the page call the functions to display the dependencies in the text area on the page. This tutorial showed how to get the dependencies of cells as well as connect custom actions to keyboard shortcuts in Spread.Sheets.

Spread.Sheets and the Month Sparkline

$
0
0

A Month sparkline can be a useful way to show data trends, such as finding the day with the highest call volume in the month.

You can use the Month sparkline in Spread.Sheets to quickly find days with the highest values.

The Month sparkline displays days horizontally and week numbers vertically. For example:

MonthDiagram

Month Sparkline Diagram

The following example shows call volume for the month. This makes it easy to spot the days with the highest call volume (Monday).

SpreadSheetsMonthSparkline

Month Sparkline

Creating a Month sparkline is simple. Use the following steps:

  1. Add a column of dates and a column of values. You can set the width and height to make the sparkline easier to see.
    activeSheet.getRange(0, -1, 1, -1, GC.Spread.Sheets.SheetArea.viewport).height(120);
    activeSheet.getRange(-1, 0, -1, 1).width(150);
    for (var rowIndex = 1; rowIndex <= 31; rowIndex++) {
    activeSheet.setValue(rowIndex, 0, new Date(2017, 0, rowIndex));
    }
    activeSheet.setValue(1,1,10, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(2,1,98, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(3,1,37, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(4,1,50, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(5,1,75, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(6,1,25, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(7,1,25, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(8,1,30, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(9,1,22, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(10,1,82, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(11,1,89, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(12,1,43, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(13,1,15, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(14,1,12, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(15,1,15, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(16,1,54, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(17,1,77, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(18,1,39, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(19,1,20, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(20,1,65, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(21,1,20, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(22,1,20, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(23,1,20, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(24,1,18, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(25,1,20, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(26,1,42, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(27,1,21, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(28,1,20, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(29,1,9, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(30,1,99, GC.Spread.Sheets.SheetArea.viewport);
    activeSheet.setValue(31,1,59, GC.Spread.Sheets.SheetArea.viewport);
  2. Use the setFormula method to add the Month sparkline. Specify the year, month, cell range, and sparkline colors.
    activeSheet.setFormula(0, 0, '=MONTHSPARKLINE(2017,1,A2:B32,"lightyellow","lightgreen","green","tomato")');
    spread.resumePaint();

That is all the code you need to create a Month sparkline.

Here is the complete code example:

<!DOCTYPE html>
<html>
<head>
<title>SpreadSheets</title>
<link href="./css/gc.spread.sheets.9.40.20153.0.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="./scripts/gc.spread.sheets.all.9.40.20153.0.min.js"></script>
<script src="http://code.jquery.com/jquery-2.0.2.js" type="text/javascript"></script>
<script type="text/javascript">
window.onload = function(){
var spread = new GC.Spread.Sheets.Workbook(document.getElementById("ss"),{sheetCount:3});
var activeSheet = spread.getActiveSheet();
activeSheet.getRange(0, -1, 1, -1, GC.Spread.Sheets.SheetArea.viewport).height(120);
activeSheet.getRange(-1, 0, -1, 1).width(150);
for (var rowIndex = 1; rowIndex <= 31; rowIndex++) {
activeSheet.setValue(rowIndex, 0, new Date(2017, 0, rowIndex));
}
activeSheet.setValue(1,1,10, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(2,1,98, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(3,1,37, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(4,1,50, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(5,1,75, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(6,1,25, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(7,1,25, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(8,1,30, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(9,1,22, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(10,1,82, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(11,1,89, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(12,1,43, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(13,1,15, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(14,1,12, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(15,1,15, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(16,1,54, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(17,1,77, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(18,1,39, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(19,1,20, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(20,1,65, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(21,1,20, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(22,1,20, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(23,1,20, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(24,1,18, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(25,1,20, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(26,1,42, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(27,1,21, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(28,1,20, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(29,1,9, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(30,1,99, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setValue(31,1,59, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.setFormula(0, 0, '=MONTHSPARKLINE(2017,1,A2:B32,"lightyellow","lightgreen","green","tomato")');
spread.resumePaint();
}
</script>
</head>
<body>
<div id="ss" style="height: 350px; width: 600px"></div>
</body>
</html>

Spread for Windows Forms and the GcComboBox Cell

$
0
0

A combo box can be useful when creating a form for users such as an on-line order form.

The new GcComboBox cell in Spread for Windows Forms allows you to set different backcolors for each list item. The GcComboBox also has a resize icon that allows you to resize the drop-down list. Both the GcComboBox cell and the original Spread combo box cell allow you to add images to the drop-down list. The GcComboBox cell can display the image in the edit area with the TextBoxStyle property.

The following example creates a simple form that displays a price when you select from a list of dessert flavors.

gccombo

GcComboBox Cell

selected

Selected Item

Use the following steps to create this example:

  1. Add images to an image list.
    ImageList img = new ImageList();
    img.Images.Add(Image.FromFile("C:\\Program Files (x86)\\GrapeCity\\rasp.png"));
    img.Images.Add(Image.FromFile("C:\\Program Files (x86)\\GrapeCity\\vanilla.png"));
    img.Images.Add(Image.FromFile("C:\\Program Files (x86)\\GrapeCity\\choco.png"));
    img.Images.Add(Image.FromFile("C:\\Program Files (x86)\\GrapeCity\\banana.png"));
  2. Create the GcComboBox cell.
    GrapeCity.Win.Spread.InputMan.CellType.GcComboBoxCellType gccombo = new GrapeCity.Win.Spread.InputMan.CellType.GcComboBoxCellType();
  3. Set cell properties and add the list items.
    gccombo.DropDownStyle = ComboBoxStyle.DropDownList;
    gccombo.Items.AddRange(new String[] { "Raspberry", "Vanilla", "Chocolate", "Banana" });
  4. Set colors and images for the list items. Assign the image list to the cell.
    gccombo.Items[0].BackColor = Color.Fuchsia;
    gccombo.Items[1].BackColor = Color.Ivory;
    gccombo.Items[2].BackColor = Color.Chocolate;
    gccombo.Items[3].BackColor = Color.LightYellow;
    gccombo.ImageList = img;
    gccombo.Items[0].Image = 0;
    gccombo.Items[1].Image = 1;
    gccombo.Items[2].Image = 2;
    gccombo.Items[3].Image = 3;
    gccombo.ShowListBoxImage = true;
  5. Set any cell formatting properties.
    gccombo.ImageAlign = HorizontalAlignment.Right;
    gccombo.ListSelectedItemStyle.BackColor = Color.Bisque;
    gccombo.ListSelectedItemStyle.ForeColor = Color.Black;
  6. Assign the cell type to the cell location.
    fpSpread1.Sheets[0].Cells[1, 1].CellType = gccombo;
  7. Add the currency cell.
    FarPoint.Win.Spread.CellType.CurrencyCellType currencycell = new FarPoint.Win.Spread.CellType.CurrencyCellType();
    fpSpread1.Sheets[0].Cells[1, 2].CellType = currencycell;
  8. Add text information and set the font and alignment.
    fpSpread1.Sheets[0].Cells[0, 1].Text = "Select a flavor";
    fpSpread1.Sheets[0].Cells[0, 2].Text = "Total";
    fpSpread1.Sheets[0].Columns[1, 2].Font = new Font("Calibri", 10, FontStyle.Bold);
    fpSpread1.Sheets[0].Columns[1, 2].HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Center;
    fpSpread1.Sheets[0].Rows[1].VerticalAlignment = FarPoint.Win.Spread.CellVerticalAlignment.Center;
  9. Use the ComboSelChange event to get the selection and set the price.
    private void fpSpread1_ComboSelChange(object sender, FarPoint.Win.Spread.EditorNotifyEventArgs e)
    {
    string caseSwitch;
    caseSwitch = fpSpread1.Sheets[0].Cells[1, 1].Text;
    switch (caseSwitch)
    {
    case "Raspberry":
    fpSpread1.Sheets[0].Cells[1, 2].Value = 5.00;
    break;
    case "Vanilla":
    fpSpread1.Sheets[0].Cells[1, 2].Value = 4.00;
    break;
    case "Chocolate":
    fpSpread1.Sheets[0].Cells[1, 2].Value = 4.25;
    break;
    case "Banana":
    fpSpread1.Sheets[0].Cells[1, 2].Value = 4.75;
    break;
    }
    }

Here is the complete example in C#:

// Select dessert flavor.
ImageList img = new ImageList();
img.Images.Add(Image.FromFile("C:\\Program Files (x86)\\GrapeCity\\rasp.png"));
img.Images.Add(Image.FromFile("C:\\Program Files (x86)\\GrapeCity\\vanilla.png"));
img.Images.Add(Image.FromFile("C:\\Program Files (x86)\\GrapeCity\\choco.png"));
img.Images.Add(Image.FromFile("C:\\Program Files (x86)\\GrapeCity\\banana.png"));
GrapeCity.Win.Spread.InputMan.CellType.GcComboBoxCellType gccombo = new GrapeCity.Win.Spread.InputMan.CellType.GcComboBoxCellType();
gccombo.DropDownStyle = ComboBoxStyle.DropDownList;
gccombo.Items.AddRange(new String[] { "Raspberry", "Vanilla", "Chocolate", "Banana" });
gccombo.Items[0].BackColor = Color.Fuchsia;
gccombo.Items[1].BackColor = Color.Ivory;
gccombo.Items[2].BackColor = Color.Chocolate;
gccombo.Items[3].BackColor = Color.LightYellow;

gccombo.ImageList = img;
gccombo.Items[0].Image = 0;
gccombo.Items[1].Image = 1;
gccombo.Items[2].Image = 2;
gccombo.Items[3].Image = 3;
gccombo.ShowListBoxImage = true;
gccombo.ImageAlign = HorizontalAlignment.Right;
gccombo.ListSelectedItemStyle.BackColor = Color.Bisque;
gccombo.ListSelectedItemStyle.ForeColor = Color.Black;
fpSpread1.Sheets[0].Cells[1, 1].CellType = gccombo;
fpSpread1.Sheets[0].Columns[1].Width = 200;
fpSpread1.Sheets[0].Rows[1].Height = 40;
FarPoint.Win.Spread.CellType.CurrencyCellType currencycell = new FarPoint.Win.Spread.CellType.CurrencyCellType();
fpSpread1.Sheets[0].Cells[1, 2].CellType = currencycell;
fpSpread1.Sheets[0].Cells[0, 1].Text = "Select a flavor";
fpSpread1.Sheets[0].Cells[0, 2].Text = "Total";
fpSpread1.Sheets[0].Columns[1, 2].Font = new Font("Calibri", 10, FontStyle.Bold);
fpSpread1.Sheets[0].Columns[1, 2].HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Center;
fpSpread1.Sheets[0].Rows[1].VerticalAlignment = FarPoint.Win.Spread.CellVerticalAlignment.Center;

private void fpSpread1_ComboSelChange(object sender, FarPoint.Win.Spread.EditorNotifyEventArgs e)
{
string caseSwitch;
caseSwitch = fpSpread1.Sheets[0].Cells[1, 1].Text;
switch (caseSwitch)
{
case "Raspberry":
fpSpread1.Sheets[0].Cells[1, 2].Value = 5.00;
break;
case "Vanilla":
fpSpread1.Sheets[0].Cells[1, 2].Value = 4.00;
break;
case "Chocolate":
fpSpread1.Sheets[0].Cells[1, 2].Value = 4.25;
break;
case "Banana":
fpSpread1.Sheets[0].Cells[1, 2].Value = 4.75;
break;
}
}

Here is the complete example in VB:

Dim img As New ImageList()
img.Images.Add(Image.FromFile("C:\Program Files (x86)\GrapeCity\rasp.png"))
img.Images.Add(Image.FromFile("C:\Program Files (x86)\GrapeCity\vanilla.png"))
img.Images.Add(Image.FromFile("C:\Program Files (x86)\GrapeCity\choco.png"))
img.Images.Add(Image.FromFile("C:\Program Files (x86)\GrapeCity\banana.png"))
Dim gccombo As New GrapeCity.Win.Spread.InputMan.CellType.GcComboBoxCellType()
gccombo.DropDownStyle = ComboBoxStyle.DropDownList
gccombo.Items.AddRange(New String() {"Raspberry", "Vanilla", "Chocolate", "Banana"})
gccombo.Items(0).BackColor = Color.Fuchsia
gccombo.Items(1).BackColor = Color.Ivory
gccombo.Items(2).BackColor = Color.Chocolate
gccombo.Items(3).BackColor = Color.LightYellow
gccombo.ImageList = img
gccombo.Items(0).Image = 0
gccombo.Items(1).Image = 1
gccombo.Items(2).Image = 2
gccombo.Items(3).Image = 3
gccombo.ShowListBoxImage = True
gccombo.ImageAlign = HorizontalAlignment.Right
gccombo.ListSelectedItemStyle.BackColor = Color.Bisque
gccombo.ListSelectedItemStyle.ForeColor = Color.Black
FpSpread1.Sheets(0).Cells(1, 1).CellType = gccombo
FpSpread1.Sheets(0).Columns(1).Width = 200
FpSpread1.Sheets(0).Rows(1).Height = 40
Dim currencycell As New FarPoint.Win.Spread.CellType.CurrencyCellType()
FpSpread1.Sheets(0).Cells(1, 2).CellType = currencycell
FpSpread1.Sheets(0).Cells(0, 1).Text = "Select a flavor"
FpSpread1.Sheets(0).Cells(0, 2).Text = "Total"
FpSpread1.Sheets(0).Columns(1, 2).Font = New Font("Calibri", 10, FontStyle.Bold)
FpSpread1.Sheets(0).Columns(1, 2).HorizontalAlignment = FarPoint.Win.Spread.CellHorizontalAlignment.Center
FpSpread1.Sheets(0).Rows(1).VerticalAlignment = FarPoint.Win.Spread.CellVerticalAlignment.Center
Private Sub FpSpread1_ComboSelChange(sender As Object, e As FarPoint.Win.Spread.EditorNotifyEventArgs) Handles FpSpread1.ComboSelChange
Dim caseSwitch As String
caseSwitch = FpSpread1.Sheets(0).Cells(1, 1).Text
Select Case caseSwitch
Case "Raspberry"
FpSpread1.Sheets(0).Cells(1, 2).Value = 5.0
Exit Select
Case "Vanilla"
FpSpread1.Sheets(0).Cells(1, 2).Value = 4.0
Exit Select
Case "Chocolate"
FpSpread1.Sheets(0).Cells(1, 2).Value = 4.25
Exit Select
Case "Banana"
FpSpread1.Sheets(0).Cells(1, 2).Value = 4.75
Exit Select
End Select
End Sub

The following help topic has information about adding the Spread component to a Visual Studio project: http://sphelp.grapecity.com/WebHelp/SpreadNet10/WF/webframe.html#spwin-vs2015add.html.

For more information about the GcComboBox cell, refer to http://sphelp.grapecity.com/WebHelp/SpreadNet10/WF/webframe.html#spwin-gccombo.html.

Spread.Sheets Excel Navigation

$
0
0

In Excel, the key combination of Ctrl and an arrow key allows the user to navigate to the end of a data region in a worksheet. While this functionality is not currently automatically provided in Spread.Sheets, it is very easy to add. In this tutorial you will learn how to overwrite default behavior for key combinations, as well as how to write custom commands.

The download for this sample can be found here: Excel Navigation

Figure1

Set Up the Project

Create a new HTML page and add references to the Spread.Sheets script and css files:


<!DOCTYPE html>
<html>
<head>
    <title>Spread.Sheets Excel Selection</title>

    <link href="http://cdn.grapecity.com/spreadjs/hosted/css/gc.spread.sheets.excel2013white.10.0.0.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="http://cdn.grapecity.com/spreadjs/hosted/scripts/gc.spread.sheets.all.10.0.0.min.js"></script>

</head>
<body>
    <div id="ss" style="height:600px ; width :100%; "></div>
</body>
</html>

Then add a script to the page that initializes the Spread.Sheets component as well as a div element to contain it:


    <script type="text/javascript">
        window.onload = function() {
            var spread = new GC.Spread.Sheets.Workbook(document.getElementById("ss"));
            var sheet = spread.getActiveSheet();
        };
    </script>
</head>
<body>
    <div id="ss" style="height:600px ; width :100%; "></div>
</body>

Custom Commands

Before replacing key bindings, we first have to write the custom commands that will be fired when hitting those specific key combinations. For tutorial purposes, we will go over one specific action for when the user presses Ctrl + Right Arrow. With that action, the selection will navigate to the end of the data region that is currently selected. Essentially, the selection will move to the next cell that has data if the current cell is empty, and it will move to the last cell with data if the current cell has data in it.

For this command, we will write a function to contain the behavior:


function customSelectRight() {
    var sheet = GC.Spread.Sheets.findControl(document.getElementById("ss")).getActiveSheet();
    var activeRowIndex = sheet.getActiveRowIndex();
    var activeColIndex = sheet.getActiveColumnIndex();
    var sheetColCount = sheet.getColumnCount();

    var findNextNotNullColIndex = function (sheet, fixRow, offset, stop) {
        while (offset < stop) {
            if (sheet.getValue(fixRow, offset) !== null) {
                break;
            }
            offset++;
        }
        return offset;
    }

    var findNextNullColIndex = function (sheet, fixRow, offset, stop) {
        while (offset < stop + 1) {
            if (sheet.getValue(fixRow, offset) == null) {
                offset--;
                break;
            }
            offset++;
        }
        return offset;
    }

    var stopSearchIndex = sheetColCount;
    var startSearchIndex = sheet.getActiveColumnIndex() + 1;

    var findResult;
    if (sheet.getValue(activeRowIndex, startSearchIndex) !== null) {
        findResult = findNextNullColIndex(sheet, activeRowIndex, startSearchIndex, stopSearchIndex);
    } else {
        findResult = findNextNotNullColIndex(sheet, activeRowIndex, startSearchIndex, stopSearchIndex);
    }

    if (findResult <= sheetColCount) {
        sheet.setActiveCell(sheet.getActiveRowIndex(), findResult);
        sheet.repaint();
    }
}

That logic goes through and figures out which column is at the end of the current data region and set’s the active cell to the cell in that column in the same row. This is just an example of one direction, and custom functions will need to be written for each direction with similar logic.

Bind Commands

After the custom functions have been written, we will need to connect the functions to specific key combinations by registering the commands with the command manager:


spread.commandManager().register('customSelectLeft', customSelectLeft);
spread.commandManager().register('customSelectRight', customSelectRight);
spread.commandManager().register('customSelectDown', customSelectDown);
spread.commandManager().register('customSelectUp', customSelectUp);

Now that the commands are registered, we can set key combinations to fire those commands. However, we must also get rid of the default behavior of each key we are binding, so that it only does the command we specify:


spread.commandManager().setShortcutKey(undefined, GC.Spread.Commands.Key.left, true, false, false, false);
spread.commandManager().setShortcutKey('customSelectLeft', GC.Spread.Commands.Key.left, true, false, false, false);
spread.commandManager().setShortcutKey(undefined, GC.Spread.Commands.Key.right, true, false, false, false);
spread.commandManager().setShortcutKey('customSelectRight', GC.Spread.Commands.Key.right, true, false, false, false);
spread.commandManager().setShortcutKey(undefined, GC.Spread.Commands.Key.down, true, false, false, false);
spread.commandManager().setShortcutKey('customSelectDown', GC.Spread.Commands.Key.down, true, false, false, false);
spread.commandManager().setShortcutKey(undefined, GC.Spread.Commands.Key.up, true, false, false, false);
spread.commandManager().setShortcutKey('customSelectUp', GC.Spread.Commands.Key.up, true, false, false, false);

Once that code has been added, the Ctrl+Arrow key combination will move to the end of the current data region in the row or column, depending on the direction. This sort of logic can be applied to other commands that you might want to implement in Spread.Sheets.

Figure1

You can learn more about Spread.Sheets and download your 30-day evaluation here.

Spread Windows Forms and the Waterfall Chart

$
0
0

A Waterfall chart is a popular visualization tool that you can now use in Spread for Windows Forms, a Visual Studio .NET control. Spread for Windows Forms also supports many other chart types. You can see a list of the many product features on our web site at http://spread.grapecity.com/spread-studio/.

Row after row of sales information can be time consuming to review. The Waterfall chart allows you to quickly see key items such as net profit when displaying company profits and expenses.

waterfallchart

Waterfall Chart

You can easily create a Waterfall chart using the Spread Designer or code.

Use the following steps to create a Waterfall chart with sales data in the Spread Designer. Refer to the following help topic for information about starting the Spread Designer: http://sphelp.grapecity.com/WebHelp/SpreadNet10/WF/webframe.html#spwin-spd-launch.html.

  1. Add your data to the designer.
  2. Select the Insert tab.
    waterfalldesign1

    Chart Data

  3. Select the Waterfall chart in the Insert Chart dialog from the Other Charts option.
    waterfalldesign2

    Add Chart

  4. Select OK.
    waterfalldesign3

    Format Chart

  5. Double-click on the data point to select the data point you want to apply colors to.
  6. Right-click on the selected data point and choose the Format Data Point option.
    waterfalldesign4

    Format Data Point

  7. Set the gradient color and then select Close.
    waterfalldesign5

    Set Color

You have now created the sample using the Spread Windows Forms designer.

Use the following steps to create the same Waterfall chart using code.

  1. Create a series object.
    FarPoint.Win.Chart.WaterfallSeries wseries = new FarPoint.Win.Chart.WaterfallSeries();
  2. Create a series name.
    wseries.SeriesName = "Series0";
  3. Add category names for your sales data.
    wseries.CategoryNames.Add("Sales Revenue");
    wseries.CategoryNames.Add("Rent");
    wseries.CategoryNames.Add("Payroll");
    wseries.CategoryNames.Add("Other Expenses");
    wseries.CategoryNames.Add("Net Profit");
  4. Add your sales values to the series.
    wseries.Values.Add(200000);
    wseries.Values.Add(-12000);
    wseries.Values.Add(-80000);
    wseries.Values.Add(-30000);
    wseries.Values.Add(78000);
  5. Add any borders or fills to improve the appearance of your chart.
    wseries.Border = new FarPoint.Win.Chart.SolidLine(Color.Black);
    wseries.Fills.AddRange(new FarPoint.Win.Chart.Fill[] { null, new FarPoint.Win.Chart.GradientFill(Color.Red, Color.Orange), new FarPoint.Win.Chart.GradientFill(Color.Red, Color.Orange), new FarPoint.Win.Chart.GradientFill(Color.Red, Color.Orange) , null});
  6. Create the plot area, set properties such as location, and add the series.
    FarPoint.Win.Chart.YPlotArea plotArea = new FarPoint.Win.Chart.YPlotArea();
    plotArea.Location = new System.Drawing.PointF(0.2f, 0.2f);
    plotArea.Size = new System.Drawing.SizeF(0.6f, 0.6f);
    plotArea.Series.Add(wseries);
    plotArea.XAxis.Title = "Company Profit";
    plotArea.XAxis.TitleOffset = 30;
  7. Create a chart model object and add the plot area.
    FarPoint.Win.Chart.ChartModel model = new FarPoint.Win.Chart.ChartModel();
    model.PlotAreas.Add(plotArea);
  8. Create a SpreadChart object, add the model, set additional properties such as the chart location, and then add the chart to the sheet.
    FarPoint.Win.Spread.Chart.SpreadChart chart = new FarPoint.Win.Spread.Chart.SpreadChart();
    chart.Model = model;
    chart.Size = new Size(800, 400);
    chart.Location = new Point(100, 100);
    fpSpread1.Sheets[0].Charts.Add(chart);

waterfallchart

These are all the steps you need to create a Waterfall chart in Spread for Windows Forms.

Here is the complete example in C#:

FarPoint.Win.Chart.WaterfallSeries wseries = new FarPoint.Win.Chart.WaterfallSeries();
wseries.SeriesName = "Series0";
wseries.CategoryNames.Add("Sales Revenue");
wseries.CategoryNames.Add("Rent");
wseries.CategoryNames.Add("Payroll");
wseries.CategoryNames.Add("Other Expenses");
wseries.CategoryNames.Add("Net Profit");
wseries.Values.Add(200000);
wseries.Values.Add(-12000);
wseries.Values.Add(-80000);
wseries.Values.Add(-30000);
wseries.Values.Add(78000);
wseries.Border = new FarPoint.Win.Chart.SolidLine(Color.Black);
wseries.Fills.AddRange(new FarPoint.Win.Chart.Fill[] { null, new FarPoint.Win.Chart.GradientFill(Color.Red, Color.Orange), new FarPoint.Win.Chart.GradientFill(Color.Red, Color.Orange), new FarPoint.Win.Chart.GradientFill(Color.Red, Color.Orange) , null});
FarPoint.Win.Chart.YPlotArea plotArea = new FarPoint.Win.Chart.YPlotArea();
plotArea.Location = new System.Drawing.PointF(0.2f, 0.2f);
plotArea.Size = new System.Drawing.SizeF(0.6f, 0.6f);
plotArea.Series.Add(wseries);
plotArea.XAxis.Title = "Company Profit";
plotArea.XAxis.TitleOffset = 30;
FarPoint.Win.Chart.ChartModel model = new FarPoint.Win.Chart.ChartModel();
model.PlotAreas.Add(plotArea);
FarPoint.Win.Spread.Chart.SpreadChart chart = new FarPoint.Win.Spread.Chart.SpreadChart();
chart.Model = model;
chart.Size = new Size(800, 400);
chart.Location = new Point(100, 100);
fpSpread1.Sheets[0].Charts.Add(chart);

Here is the complete example in Visual Basic:

Dim wseries As New FarPoint.Win.Chart.WaterfallSeries()
wseries.SeriesName = "Series0"
wseries.CategoryNames.Add("Sales Revenue")
wseries.CategoryNames.Add("Rent")
wseries.CategoryNames.Add("Payroll")
wseries.CategoryNames.Add("Other Expenses")
wseries.CategoryNames.Add("Net Profit")
wseries.Values.Add(200000)
wseries.Values.Add(-12000)
wseries.Values.Add(-80000)
wseries.Values.Add(-30000)
wseries.Values.Add(78000)
wseries.Border = New FarPoint.Win.Chart.SolidLine(Color.Black)
wseries.Fills.AddRange(New FarPoint.Win.Chart.Fill() {Nothing, New FarPoint.Win.Chart.GradientFill(Color.Red, Color.Orange), New FarPoint.Win.Chart.GradientFill(Color.Red, Color.Orange),
New FarPoint.Win.Chart.GradientFill(Color.Red, Color.Orange), Nothing})
Dim plotArea As New FarPoint.Win.Chart.YPlotArea()
plotArea.Location = New System.Drawing.PointF(0.2F, 0.2F)
plotArea.Size = New System.Drawing.SizeF(0.6F, 0.6F)
plotArea.Series.Add(wseries)
plotArea.XAxis.Title = "Company Profit"
plotArea.XAxis.TitleOffset = 30
Dim model As New FarPoint.Win.Chart.ChartModel()
model.PlotAreas.Add(plotArea)
Dim chart As New FarPoint.Win.Spread.Chart.SpreadChart()
chart.Model = model
chart.Size = New Size(800, 400)
chart.Location = New Point(100, 100)
FpSpread1.Sheets(0).Charts.Add(chart)

You can also use a data source for the chart. For example:

C#

object[] values = new object[] { 200000, -12000, -80000, -30000, 78000 };
string[] names = new string[] { "Sales Revenue", "Rent", "Payroll", "Other Expenses", "Net Profit" };
FarPoint.Win.Chart.WaterfallSeries wseries = new FarPoint.Win.Chart.WaterfallSeries();
wseries.Values.DataSource = values;
wseries.SeriesName = "Series0";
wseries.CategoryNames.DataSource = names;
wseries.Border = new FarPoint.Win.Chart.SolidLine(Color.Black);
wseries.Fills.AddRange(new FarPoint.Win.Chart.Fill[] { null, new FarPoint.Win.Chart.GradientFill(Color.Red, Color.Orange), new FarPoint.Win.Chart.GradientFill(Color.Red, Color.Orange), new
FarPoint.Win.Chart.GradientFill(Color.Red, Color.Orange), null });
FarPoint.Win.Chart.YPlotArea plotArea = new FarPoint.Win.Chart.YPlotArea();
plotArea.Location = new System.Drawing.PointF(0.2f, 0.2f);
plotArea.Size = new System.Drawing.SizeF(0.6f, 0.6f);
plotArea.Series.Add(wseries);
plotArea.XAxis.Title = "Company Profit";
plotArea.XAxis.TitleOffset = 30;
FarPoint.Win.Chart.ChartModel model = new FarPoint.Win.Chart.ChartModel();
model.PlotAreas.Add(plotArea);
FarPoint.Win.Spread.Chart.SpreadChart chart = new FarPoint.Win.Spread.Chart.SpreadChart();
chart.Model = model;
chart.Size = new Size(800, 400);
chart.Location = new Point(100, 100);
fpSpread1.Sheets[0].Charts.Add(chart);

Visual Basic

Dim values As Object() = {200000, -12000, -80000, -30000, 78000}
Dim names As String() = {"Sales Revenue", "Rent", "Payroll", "Other Expenses", "Net Profit"}
Dim wseries As New FarPoint.Win.Chart.WaterfallSeries()
wseries.Values.DataSource = values
wseries.SeriesName = "Series0"
wseries.CategoryNames.DataSource = names
wseries.Border = New FarPoint.Win.Chart.SolidLine(Color.Black)
wseries.Fills.AddRange(New FarPoint.Win.Chart.Fill() {Nothing, New FarPoint.Win.Chart.GradientFill(Color.Red, Color.Orange), New FarPoint.Win.Chart.GradientFill(Color.Red, Color.Orange),
New FarPoint.Win.Chart.GradientFill(Color.Red, Color.Orange), Nothing})
Dim plotArea As New FarPoint.Win.Chart.YPlotArea()
plotArea.Location = New System.Drawing.PointF(0.2F, 0.2F)
plotArea.Size = New System.Drawing.SizeF(0.6F, 0.6F)
plotArea.Series.Add(wseries)
plotArea.XAxis.Title = "Company Profit"
plotArea.XAxis.TitleOffset = 30
Dim model As New FarPoint.Win.Chart.ChartModel()
model.PlotAreas.Add(plotArea)
Dim chart As New FarPoint.Win.Spread.Chart.SpreadChart()
chart.Model = model
chart.Size = New Size(800, 400)
chart.Location = New Point(100, 100)
FpSpread1.Sheets(0).Charts.Add(chart)

You can download a trial of Spread for Windows Forms here: http://spread.grapecity.com/downloads/.

You can find more information about Spread Studio .NET here: http://spread.grapecity.com/spread-studio/.


Spread.Sheets and JS Bin

$
0
0

You can now test Spread.Sheets in JS Bin with a special license key. Spread.Sheets can be used in browser applications that support HTML5. For more information about Spread.Sheets, refer to http://spread.grapecity.com/spreadjs/sheets/.

The following example shows you how to add Spread.Sheets to a JS Bin project. JS Bin is located at jsbin.com.

  1. Add references to Spread.Sheets in the HTML window. You can also add references to any other libraries.
  2. Add the Spread tag to the HTML window.
    spreadsheetsbin1

    References

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>JS Bin</title>
    </head>
    <body>
    <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
    <link href="https://cdn.grapecity.com/spreadjs/hosted/css/gc.spread.sheets.excel2016colorful.10.0.0.css" rel="stylesheet" type="text/css"/>
    <script type="text/javascript" src="https://cdn.grapecity.com/spreadjs/hosted/scripts/gc.spread.sheets.all.10.0.0.min.js"></script>
    <div id="ss" style="width:80%;height:500px;border:1px solid gray"></div>
    </body>
    </html>
  3. Add the Spread.Sheets license to the JavaScript window. Then add code to create the Spread object.
    spreadsheetsbin2

    Spread License

    GC.Spread.Sheets.LicenseKey = "E612148219772179#A04NZkTMygDNxITM6IiOiQWSisnOiQkIsISP3EUOCpVRpFGVQple9cmS7ZnYNh7SBpURvYWeHVEaBdmcstWM5wmQxIHeQ5kdHNlZSN6NDB5L4dTVIlmRGhTczA7ai9Gqd7NDNjMyhVSu34UOpGT7V5RiojITJCLxEzMyEDOyUTO0IicfJye#4Xfd5nIxcEMBJiOiMkIsICMx8idgMlSgQWYlJHcTJiOi8kI1tlOiQmcQJCLiETM5UDNwASMyMDM7EDMyIiOiQncDJCLiQXZu9SZsRGZpZ6cqxSbvNmLulmYzpmI0IycRkIsIyZuFWWggXZsFkI0ISYONkIsUWdyRnOiwmdFJCLikXNZI";
    var spread = new GC.Spread.Sheets.Workbook(document.getElementById("ss"),{sheetCount:3});
    var activeSheet = spread.getActiveSheet();

That is all you have to do to use Spread.Sheets in JS Bin.

SpreadSheetsBinV10

SpreadJS V10 SP1 Release

$
0
0

SpreadJS V10 SP1 has now been released. This release fixes many reported issues. Here is a list of the resolved issues:

  • Spread now works correctly with a list validator. [230436]
  • The formula text box is now initialized correctly. [230201]
  • The copyTo method now works correctly when using arrow keys to select data. [230117]
  • The designer now correctly loads certain Excel-formatted files. [229685]
  • Copying a range that contains a formula error now works correctly. [229438]
  • Spread now works correctly with the Apple Magic mouse. [229314]
  • Exporting to an Excel-formatted file on a MAC now works correctly. [229155]
  • The custom culture list separator now works correctly with the formula text box. [229050]
  • Copying from a text editor to Spread now works correctly. [228942]
  • Performance has been enhanced when loading JSON files. [228576]
  • The resumeCalcService method now works correctly when pasting conditional formatting. [228445]
  • Pasting data from Excel has been enhanced. [228424]
  • The SelectionChanged event now works correctly. [228393]
  • The formula text box is now updated when using the setActiveSheet method. [228391]
  • The Enter key now works in some dialogs in the designer. [228016]
  • Frozen rows and columns now work correctly when leaving edit mode in a cell. [227553]
  • The all option in the ClipboardPasteOptions enumeration now works correctly with conditional formatting. [227261]
  • Filtering now works correctly. [226718]
  • The RangeChanged event now works correctly. [226395]
  • The INDEX formula now works correctly. [226384]
  • Custom names now work correctly with parentheses. [225658]
  • Decimal values now work correctly with Finnish culture settings. [225057]
  • Pasting now works correctly when the copyPasteHeaderOptions enumeration is set to allHeaders. [225038]
  • The allowExtendPasteRange option now works correctly when Spread is bound using the setDataSource method. [224735]
  • Dates are now displayed correctly when editing. [224638]
  • Formulas now update correctly when inserting cells. [223884]
  • The setRowVisible and setColumnVisible methods now work correctly. [223877]
  • Named styles are now exported correctly. [223707]
  • Copying and pasting data now works correctly. [223242]
  • Formulas are now updated correctly. [222576]
  • The designer now exports SSJSON files correctly. [222218]
  • Formatting now works correctly with certain culture settings. [221978]
  • The migration file has been updated. [221858]
  • Binding to an empty data source now works correctly. [221842]

The ReadMe is located here: http://sphelp.grapecity.com/WebHelp/SpreadSheets10ReadMe/webframe.html#readme.html.

You can get the download here: http://spread.grapecity.com/downloads/.

Spread Studio V10 SP1 Release

$
0
0

Spread Studio V10 SP1 has now been released. This release adds support for Microsoft Visual Studio 2017 and fixes many reported issues. Here is a list of the resolved issues:

Spread Windows Forms:

  • X-axis labels are now correctly imported or exported. [227346]
  • Clearing the focus indicator now works correctly. [226341]

Spread ASP.NET:

  • Getting the font now works correctly. [230439]
  • Spread no longer loads duplicate script files with MVC. [228660]
  • Performance has been enhanced when editing cells. [224979]
  • Hyperlink cells now work correctly in the last visible column. [224704]
  • Spread now works correctly when the column header contains an ampersand. [224149]
  • The SaveHTML method now works correctly. [220869]

Spread WPF:

  • Formulas are now updated correctly when adding columns. [230048]

You can get more information in the ReadMe: http://sphelp.grapecity.com/WebHelp/SpreadStudio10ReadMe/webframe.html#ReadMe.html.

You can get the download here: http://spread.grapecity.com/downloads/.

Spread.Sheets and JSFiddle

$
0
0

You can now test Spread.Sheets in JSFiddle with a special license key. Spread.Sheets can be used in browser applications that support HTML5. For more information about Spread.Sheets, refer to http://spread.grapecity.com/spreadjs/sheets/.

The following example shows you how to add Spread.Sheets to a JSFiddle project. JSFiddle is located at https://jsfiddle.net/.

  1. Select External Resources to add the Spread.Sheets and any other references.
    SpreadSheetsJSFiddle1

    Select External Resources

  2. Paste the reference in the text area to the left of the plus icon. Select the plus icon to add the reference. Repeat for each reference.
    SpreadSheetsJSFiddle2

    Add References

    SpreadSheetsJSFiddle3

    Added References

    https://code.jquery.com/jquery-2.1.1.min.js
    
    https://cdn.grapecity.com/spreadjs/hosted/css/gc.spread.sheets.excel2016colorful.10.1.0.css
    
    https://cdn.grapecity.com/spreadjs/hosted/scripts/gc.spread.sheets.all.10.1.0.min.js
  3. Paste the Html tags for Spread in the HTML section.SpreadSheetsJSFiddle4
    <div id="ss" style="width: 600px; height: 550px; border: 1px solid gray">
  4. Add the license key and create a Spread object in the JavaScript section.SpreadSheetsJSFiddle5
    GC.Spread.Sheets.LicenseKey = "GrapeCity-Internal-Use-Only,*.jshell.net|jshell.net,E763987199884888#A06OtEzN8kzM6cjI0ICZJJCL3V6csFmZ0IiczRmI1pjIs9WQisnOiQkIsISP3cGUqRzNBlGRhR5KDVkb8kXVr26dwlDUpJmVLF4a72SRQtCbKF7RPdGSwRXTwNkVstUrknVJl6VDZXUWFUVGVkVEh6TChVRvMzKuJlSi5kZvsWQFVVbiojITJCL8gjNykjN7YTO0IicfJye#4Xfd5nIxcEMBJiOiMkIsICMx8idgMlSgQWYlJHcTJiOi8kI1tlOiQmcQJCLiIzM7QjMwASOyMDM7EDMyIiOiQncDJCLigjM4AzNxAjMiojIwhXRiwiI4VmbuwGblh6cxCdl9mLsxWZoNnauoiI0IyctRkIsIyZuFWWg2mQiojIh94QiwSZ5JHd0ICb6VkIsICO8g5Ndg";
    var spread = new GC.Spread.Sheets.Workbook(document.getElementById("ss"),{sheetCount:3});
    var activeSheet = spread.getActiveSheet();
  5. Select Run.
    SpreadSheetsJSFiddle

    Sample Project

That is all you need to do to use Spread.Sheets in JSFiddle.

How to Import/Export Excel files using JavaScript and Spread.Sheets

$
0
0

JavaScript is a versatile platform that allows easy customization of client-side scripting tools. In some applications, it is useful to have some sort of spreadsheet interface that is easy to code and maintain. The Spread.Sheets client-side JavaScript spreadsheet component, part of the SpreadJS package, is perfect for this. You can import and export Excel files, and provide users with an interface to interact with those files, all in pure JavaScript. In this tutorial, I will show you how easy it is to add a Spread.Sheets component to an HTML page and import an Excel file into it.

The download for this sample can be found here

The finished page after importing and editing an Excel file.

The finished page after importing and editing an Excel file.

Set Up the Project

Create a new HTML page and add references to the Spread.Sheets script and the CSS files that are included in your SpreadJS download:


<!DOCTYPE html>
<html>
<head>
    <title>Spread.Sheets ExcelIO</title>

    <script src="http://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script>
    <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.min.js" type="text/javascript"></script>

    <link href="http://cdn.grapecity.com/spreadjs/hosted/css/gc.spread.sheets.excel2013white.10.1.0.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="http://cdn.grapecity.com/spreadjs/hosted/scripts/gc.spread.sheets.all.10.1.0.min.js"></script>
    <script type="text/javascript" src="http://cdn.grapecity.com/spreadjs/hosted/scripts/interop/gc.spread.excelio.10.1.0.min.js"></script>

</head>
<body>
    <div id="ss" style="height:600px ; width :100%; "></div>
</body>
</html>

Then add a script to the page that initializes the Spread.Sheets component, and a div element to contain it (since Spread.Sheets utilizes a canvas, this is necessary to initialize the component):


    <script type="text/javascript">
        $(document).ready(function () {
            var workbook = new GC.Spread.Sheets.Workbook(document.getElementById("ss"));
        });
    </script>
</head>
<body>
    <div id="ss" style="height:600px ; width :100%; "></div>
</body>

Add Excel Import Code

We need to create an instance of the client-side ExcelIO component that we can use to actually open the file:


var excelIO = new GC.Spread.Excel.IO();

Then we need to add a function to import a file. In this example, we import a local file, but you can do the same thing with a file on a server.

If you’re importing a file from a server, you need to reference the location. The following is an example of an input element where the user can enter the location of the file:


<input type="text" id="importUrl" value="http://www.testwebsite.com/files/TestExcel.xlsx" style="width:300px" />

Once you have that, you can directly access that value in script code:


var excelUrl = $("#importUrl").val();

The following code for the import function just uses a local file for the “excelUrl” variable:


function ImportFile() {
    var excelUrl = "./test.xlsx";

    var oReq = new XMLHttpRequest();
    oReq.open('get', excelUrl, true);
    oReq.responseType = 'blob';
    oReq.onload = function () {
        var blob = oReq.response;
        excelIO.open(blob, LoadSpread, function (message) {
            console.log(message);
        });
    };
    oReq.send(null);
}
function LoadSpread(json) {
    jsonData = json;
    workbook.fromJSON(json);

    workbook.setActiveSheet("Revenues (Sales)");
}

Regardless of whether you are referencing a file on a server or locally, you will need to add the following to your script inside the $(document).ready function:


$(document).ready(function () {
    $.support.cors = true;
    workbook = new GC.Spread.Sheets.Workbook(document.getElementById("ss"));
    //...
});

Adding Data to the Excel File

In this tutorial, we import a local file that uses the “Profit loss statement” Excel template.

The Excel Template

The Excel Template

Now we can use Spread.Sheets script to add another revenue line into this file. Let’s add a button to the page that will do just that:


<button id="addRevenue">Add Revenue</button>

We can write a function for the click event handler for that button to add a row and copy the style from the previous row in preparation for adding some data. To copy the style, we will need to use the copyTo function and pass in:

  • the origin and destination row and column indices
  • row and column count
  • the CopyToOptions value for style

document.getElementById("addRevenue").onclick = function () {
    var sheet = workbook.getActiveSheet();
    sheet.addRows(11, 1);
    sheet.copyTo(10, 1, 11, 1, 1, 29, GC.Spread.Sheets.CopyToOptions.style);
}

All of the following script code for adding data and a Sparkline will be contained within this button click event handler. For most of the data, we can use the setValue function. This allows us to set a value in a sheet in Spread by passing in a row index, column index, and value:


sheet.setValue(11, 1, "Revenue 8");

for (var c = 3; c < 15; c++) {
    sheet.setValue(11, c, Math.floor(Math.random() * 200) + 10);
}

Set a SUM formula in column P to match the other rows and set a percentage for column Q:


sheet.setFormula(11, 15, "=SUM([@[Jan]:[Dec]])")
sheet.setValue(11, 16, 0.15);

Lastly, we can copy the formulas from the previous rows to the new row for columns R through AD using the copyTo function again, this time using CopyToOptions.formula:


sheet.copyTo(10, 17, 11, 17, 1, 13, GC.Spread.Sheets.CopyToOptions.formula);

Adding a Sparkline

Now we can add a sparkline to match the other rows of data. To do this, we need to provide a range of cells to get the data from and some settings for the sparkline. In this case, we can specify:

  • the range of cells we just added data to
  • settings to make the sparkline look like the other sparklines in the same column

var data = new GC.Spread.Sheets.Range(11, 3, 1, 12);
var setting = new GC.Spread.Sheets.Sparklines.SparklineSetting();
setting.options.seriesColor = "Text 2";
setting.options.lineWeight = 1;
setting.options.showLow = true;
setting.options.showHigh = true;
setting.options.lowMarkerColor = "Text 2";
setting.options.highMarkerColor = "Text 1";

After that, we call the setSparkline method and specify:

  • a location for the sparkline
  • the location of the data
  • the orientation of the sparkline
  • the type of sparkline
  • the settings we created

sheet.setSparkline(11, 2, data, GC.Spread.Sheets.Sparklines.DataOrientation.horizontal, GC.Spread.Sheets.Sparklines.SparklineType.line, setting);

If you were to try running the code now, it might seem a little slow because the workbook is repainting every time data is changed and styles are added. To drastically speed it up and increase performance, Spread.Sheets provides the ability to suspend painting and the calculation service. Let’s add the code to suspend both before adding a row and its data, and then resume both after:


workbook.suspendPaint();
workbook.suspendCalcService();
//...
workbook.resumeCalcService();
workbook.resumePaint();

Once we add that code, we can open the page in a web browser and see the Excel file load into Spread.Sheets with an added revenue row.

Important: Keep in mind that Chrome doesn’t allow you to open local files for security purposes, so you need to use a web browser like Firefox to successfully run this code. Alternatively, if you load a file from a website URL, it should open fine in any browser.

The Excel Template

The Excel Template

The page with a button for adding a revenue row

The page with a button for adding a revenue row

Adding Excel Export Code

Finally, we can add a button to export the file with the added row. To do this, we can use the client-side ExcelIO code built into Spread.Sheets:


function ExportFile() {
    var fileName = $("#exportFileName").val();
    if (fileName.substr(-5, 5) !== '.xlsx') {
        fileName += '.xlsx';
    }
    var json = JSON.stringify(workbook.toJSON());

    excelIO.save(json, function (blob) {
        saveAs(blob, fileName);
    }, function (e) {
        if (e.errorCode === 1) {
            alert(e.errorMessage);
        }
    });
}

That code gets the export file name from an exportFileName input element. We can define it and let users name the file like so:


<input type="text" id="exportFileName" placeholder="Export file name" value="export.xlsx" />

Then we can add a button that calls this function:


<button id="export">Export File</button>

document.getElementById("export").onclick = function () {
    ExportFile();
}
The finished page after importing and editing an Excel file.

The finished page after importing and editing an Excel file.

Once you add a revenue row, you can export the file using the Export File button. Make sure to add the FileSaver external library to allow users to save the file where they want:


<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2014-11-29/FileSaver.min.js"></script>

When the file is successfully exported, you can open it in Excel and see that the file looks like it did when it was imported, except there is now an extra revenue line that we added.

The exported file loaded into Excel

The exported file loaded into Excel

This is just one example of how you can use Spread.Sheets to add data to your Excel files and then export them back to Excel with simple JavaScript code.

You can learn more about Spread.Sheets and download your 30-day evaluation here.

Viewing all 105 articles
Browse latest View live