Kendo UI for Angular Exporting selected rows to Excel - kendo-ui

I'm using Kendo UI for Angular and I am trying to export my grid to Excel. I have implemented a solution like this: https://www.telerik.com/kendo-angular-ui/components/grid/export/excel-export/
and it does work. It exports all rows in my grid. My problem is that I only want to export selected rows. I haven't been able to successfully filter the allData method to only export selected rows.
It looks to me like the process method called from within the allData method can take a State object that has a filter: component. But for the life of me I can't seem to get it to work. Can anybody point me to a simple example where the selected rows only are exported to Excel?
Thanks,
John B.

I have implemented selected rows and selection key to be entire row so that when I export i can retrieve the selected rows and modified export allData to export selection data if exists.If selection doesnot exists then exports all data.
public mySelectionKey(context: RowArgs): string {
// return context.dataItem.serialNumber + " " + context.index;
return context.dataItem;
}
public allData(): ExcelExportData {
let selInventory: Inventory[] = [];
let result: ExcelExportData;
selInventory = JSON.parse(JSON.stringify(this.mySelection));
if (selInventory.length > 0) {
result = {
data: process(selInventory, {
sort: [{ field: "serialNumber", dir: "asc" }]
}).data
};
} else {
result = {
data: process(this.inventoryData, {
sort: [{ field: "serialNumber", dir: "asc" }]
}).data
};
}
return result;
}

Export selected or all rows
function excelExport() {
var exportAll = $('.selectrow').is(":checked");
var grid = $("#grid");
var rows = [{
cells: [
{ value: "column1" },
{ value: "column2" },
{ value: "column3" },
{ value: "column4" },
{ value: "column5" },
{ value: "column6" },
{ value: "column7" }
]
}];
if (exportAll) {
var dataDource = grid.getKendoGrid();
var trs = $("#grid").find('tr');
for (var i = 0; i < trs.length; i++) {
if ($(trs[i]).find(":checkbox").is(":checked")) {
var dataItem = dataDource.dataItem(trs[i]);
rows.push({
cells: [
{ value: dataItem.column1 },
{ value: dataItem.column2 },
{ value: dataItem.column3 },
{ value: dataItem.column4 },
{ value: dataItem.column5 },
{ value: dataItem.column6 },
{ value: dataItem.column7 }
]
})
}
}
}
else {
var dataSource = grid.data("kendoGrid").dataSource;
var trs = grid.find('tr');
for (var i = 1; i < dataSource._data.length; i++) {
var dataItem = dataSource._data[i];
rows.push({
cells: [
{ value: dataItem.column1 },
{ value: dataItem.column2 },
{ value: dataItem.column3 },
{ value: dataItem.column4 },
{ value: dataItem.column5 },
{ value: dataItem.column6 },
{ value: dataItem.column7 }
]
})
}
}
var workbook = new kendo.ooxml.Workbook({
sheets: [
{
columns: [
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true }
],
title: "Exported Result",
rows: rows
}
]
});
kendo.saveAs({ dataURI: workbook.toDataURL(), fileName: "ExportedResult" });
}

Related

Multiple sort on Kendo Grid columns / DataSource - set sorting dynamically

What I'm trying to accomplish is to apply an "automatic" secondary column sort when a user sorts a column in a kendo grid.
So in this JS fiddle example, if a user sorts by "Value", it'll also sort by "Name". Note that the 0s are sorted together, but the names aren't alphabetical. I'd like them to be alphabetical (the secondary sort).
Here's an attempt at overriding the datasource sorting to accomplish this. I'm taking the user's original sort and the adding an additional sort on "SortedName". Based on the sorting array that's logged, it seems to be close but is still not working.
Any other ideas on how to accomplish this?
Note: I don't want to allow users to sort by multiple columns. The real world example I'm using this for can have up to 50+ columns (unfortunately), so multiple sort can get confusing / unintuitive. And I'd like it to be done behind the scenes without extra user interaction.
Example code for overriding kendo datasource sort():
dataSource.originalSort = dataSource.sort;
dataSource.sort = function () {
// take the user's sort and apply sorting on an additional column
// the sort array should look like this:
[
{ field: "Value", dir: "asc" }, // this is what the user sorted by
{ field: "SortedName", dir: "asc" }, // and I'm adding this
]
return dataSource.originalSort.apply(this, arguments);
}
Please try with the below code snippet.
<div id="grid">
</div>
<script>
var dataSource = new kendo.data.DataSource({
data: [
{ Name: "Lisa", Value: 1 },
{ Name: "Dan", Value: 12 },
{ Name: "Ken", Value: 5 },
{ Name: "Arthur", Value: 15 },
{ Name: "Bob", Value: 0 },
{ Name: "Sally", Value: 0 },
{ Name: "Alexis", Value: 0 },
{ Name: "Cody", Value: 0 },
{ Name: "Steve", Value: 0 },
{ Name: "Andrew", Value: 0 },
{ Name: "Duke", Value: 0 }
],
schema: {
model: {
fields: {
Name: { type: "string" },
Value: { type: "number" }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
dataBound: function (e) {
var isSortedByName = false;
var grid = $("#grid").data("kendoGrid");
var ds = grid.dataSource;
var sort = ds.sort();
if (sort) {
for (var i = 0; i < sort.length; i++) {
if (sort[i].field == "Name") {
isSortedByName = true;
}
}
if (isSortedByName == false) {
sort.push({ field: "Name", dir: "asc" });
ds.sort(sort);
}
}
},
columns: [
{ field: "Name" },
{ field: "Value" }
],
sortable: true
});
</script>

Using Multiselect in row filter, kendo ui grid

Below is a sample of integrating multiselect with kendo ui filter row.
http://dojo.telerik.com/eriMA
<div id="grid"></div>
<script>
$("#grid").kendoGrid({
autoBind:true,
columns: [
{
field: "color",
filterable: {
cell: {
template: function (args) {
// create a MultiselectList of unique values (colors)
args.element.kendoMultiSelect({
dataSource: args.dataSource,
dataTextField: "color",
dataValueField: "color",
valuePrimitive: true,
// tagMode: true
});
},
showOperators: false
}
}
},
{ field: "age" } ],
filterable: { mode: "row" },
dataSource: { data: [ { color: "#ff0000", age: 30 }, { color: "#000000", age: 33 }], requestStart: onRequestStart }});
function onRequestStart(e){
var filter = e.sender.filter();
if (filter && filter.filters && filter.filters.length > 0) {
var filter1 = filter.filters;
for (var i = 0; i < filter1.length; i++) {
if (filter1[i].field == "color" && filter1[i].value) {
var colorList = filter1[i].value.split(",");
if (colorList.length > 0) {
var newFilter = { logic: "or", filters: [] };
for (var k = 0; k < colorList.length; k++) {
newFilter.filters.push({ field: "color", operator: "eq", value: colorList[k] });
}
filter1 = filter1.splice(i, 1, newFilter);
e.preventDefault();
e.sender.filter(filter);
}
}
}
}
}
</script>
Now, I want to set a default filter for the grid. For that I have created another sample.
http://dojo.telerik.com/eriMA/2
But unfortunately, if the grid dataSource data is initially empty, the multiselect value gets reset with first value. However, the data is filtered correctly. Can somebody help to overcome this limitation.
I have identified that somehow the filter cell get cleared after the dataBound event, if the dataSource is emtpy. So I set the value back using a timeout.
here is the link to updated source. http://dojo.telerik.com/eriMA/7
<div id="grid"></div>
<script>
var colorMulti = null;
var grid = $("#grid").kendoGrid({
autoBind:false,
columns: [
{
field: "ShipCity",
filterable: {
cell: {
template: function (args) {
// create a MultiselectList of unique values (colors)
colorMulti =args.element.kendoMultiSelect({
dataSource: {data : ["Lyon","Graz","Bern"]},
valuePrimitive: true,
// tagMode: true
}).data("kendoMultiSelect");
},
showOperators: false
}
}
},
{ field: "OrderID" } ],
filterable: { mode: "row" },
dataSource: {
type: "odata",
transport: {
read: "//demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
},
schema: {
model: {
fields: {
OrderID: { type: "number" },
Freight: { type: "number" },
ShipName: { type: "string" },
OrderDate: { type: "date" },
ShipCity: { type: "string" }
}
}
},
pageSize: 20,
requestStart:onRequestStart
},
dataBound: onDataBound
}).data("kendoGrid");
function onRequestStart(e){
var filter = e.sender.filter();
if (filter && filter.filters && filter.filters.length > 0) {
var filter1 = filter.filters;
for (var i = 0; i < filter1.length; i++) {
if (filter1[i].field == "ShipCity" && filter1[i].value) {
var colorList = filter1[i].value.split(",");
if (colorList.length > 0) {
var newFilter = { logic: "or", filters: [] };
for (var k = 0; k < colorList.length; k++) {
newFilter.filters.push({ field: "ShipCity", operator: "eq", value: colorList[k] });
}
filter1 = filter1.splice(i, 1, newFilter);
e.preventDefault();
e.sender.filter(filter);
}
}
}
}
}
function onDataBound(e){
var multiSelectValue = [];
var filter = grid.dataSource.filter();
if (filter && filter.filters && filter.filters.length > 0) {
var filter1 = filter.filters;
for (var i = 0; i < filter1.length; i++) {
if (filter1[i].field == "ShipCity" && filter1[i].value) {
multiSelectValue.push(filter1[i].value);
} else if (filter1[i].filters && filter1[i].filters.length > 0 && filter1[i].logic == "or") {
var filter2 = filter1[i].filters;
var multiSelectValue = [];
for (var j = 0; j < filter2.length; j++) {
if (filter2[j].field == "ShipCity") {
multiSelectValue.push(filter2[j].value);
}
}
}
}
}
setTimeout(function () { colorMulti.value(multiSelectValue) });
}
$(document).ready(function () {
grid.dataSource.filter({ "filters": [{ "operator": "eq", "value": "Lyon,Graz,Bern", "field": "ShipCity" }], "logic": "and" });
});
</script>

KendoUI Grid: Non-editable column?

http://jsfiddle.net/bhoff/ZCyPx/50/
$("#grid").kendoGrid({
dataSource:{
data:entries,
schema:{
parse:function (response) {
$.each(response, function (idx, elem) {
if (elem.time && typeof elem.time === "string") {
elem.time = kendo.parseDate(elem.time, "HH:mm:ss");
}
if (elem.datetime && typeof elem.datetime === "string") {
elem.datetime = kendo.parseDate(elem.datetime, "HH:mm:ss");
}
});
return response;
}
}
},
columns:[
{ command: [ "edit" ] },
{ field:"type", title:"Cash Transation Type" },
{ field:"begintime", title:"Begin Time(CT)", format:"{0:hh:mm tt}", editor: timeEditor },
{ field:"endtime", title:"End Time(CT)", format:"{0:hh:mm tt}", editor: timeEditor },
],
editable:"inline",
navigatable:true
});
Based on my example how do I stop the user from editing my "Cash Transation Type" column?
Does it have something to do with this -> editable:"inline" ?
look here
you need to set in the datasource
<script>
var dataSource = new kendo.data.DataSource({
schema: {
model: {
id: "ProductID",
fields: {
ProductID: {
//this field will not be editable (default value is true)
editable: false,
// a defaultValue will not be assigned (default value is false)
nullable: true
},
ProductName: {
//set validation rules
validation: { required: true }
},
UnitPrice: {
//data type of the field {Number|String|Boolean|Date} default is String
type: "number",
// used when new model is created
defaultValue: 42,
validation: { required: true, min: 1 }
}
}
}
}
});
</script>
You would normally set this on your DataSource on the schema.model.fields.
var data = new kendo.data.DataSource({
schema: {
model: {
fields: {
type: { editable: "false" }
Add editable in the field you do not want to enable Edit,
columns:[
{ command: [ "edit" ] },
{ field:"type", title:"Cash Transation Type", editable: false },
{ field:"begintime", title:"Begin Time(CT)", format:"{0:hh:mm tt}", editor: timeEditor },
{ field:"endtime", title:"End Time(CT)", format:"{0:hh:mm tt}", editor: timeEditor },
],
editable:"inline",
navigatable:true
});

Saving a Kendo datasource using jStorage

I'm adding and removing data to a Kendo dataSource. I wish to save it localStorage, and be able to read it again from localStorage.
Here I've attempted to use jStorage for the saving and loading of data.
How it's loaded:
if ($.jStorage.get('favoritter') != null) {
var datakilde_favoritter = $.jStorage.get('favoritter');
} else {
var data = [
{id: 5, name: "LINK ONE", url: "http://www.linkone.com" }
];
var datakilde_favoritter = new kendo.data.DataSource({
data: data,
sort: { field: "name", dir: "asc" }
});
}
How it's saved:
$.jStorage.set('favoritter', datakilde_favoritter);
Define your DataSource as:
var ds = new kendo.data.DataSource({
transport: {
read : function (op) {
var data = $.jStorage.get('favoritter');
if (!data) {
data = [
{id: 5, name: "LINK ONE", url: "http://www.linkone.com" }
];
}
op.success(data);
},
update : function (op) {
$.jStorage.set("favoritter", ds.data());
op.success(op.data);
},
destroy: function (op) {
console.log("destroy", ds.data());
$.jStorage.set("favoritter", ds.data());
op.success(op.data);
},
create : function (op) {
$.jStorage.set("favoritter", ds.data());
op.success(op.data);
}
},
sort : { field: "name", dir: "asc" },
pageSize : 10,
schema : {
model: {
id : "id",
fields: {
id : { type: 'number' },
name: { type: 'string' }
}
}
}
});
You might consider removing create and destroy if not needed.
And your grid would be something like:
var grid = $("#grid").kendoGrid({
dataSource: ds,
editable : "popup",
pageable : true,
toolbar : ["create"],
columns : [
{ command: ["edit", "destroy"], width: 100 },
{ field: "id", width: 90, title: "#" },
{ field: "name", width: 90, title: "URL Name" }
]
}).data("kendoGrid");
Basically when updating you need to invoke op.success with the data returned from the server. In your case since it is the browser itself, you don't need just to return the original data.

Data not being displayed in kendo UI grid

I have the following code
var entries = [
{ "value":"AAPL", "data":665.24, "shares":100 },
{ "value":"AMZN", "data":248.27, "shares":100 },
{ "value":"IBM", "data":194.85, "shares":100 },
{ "value":"CSCO", "data":19.08, "shares":100 },
{ "value":"MSFT", "data":30.82, "shares":100 },
{ "value":"INTC", "data":24.83, "shares":100 },
{ "value":"QCOM", "data":61.46, "shares":100 },
{ "value":"ORCL", "data":31.65, "shares":100 },
{ "value":"HPQ", "data":16.88, "shares":100 },
{ "value":"CRM", "data":145.18, "shares":100 }
];
var kendogridds = new kendo.data.DataSource({data:entries,
schema:{
model:{
fields:{
value:{ type:"string" },
data:{ type:"string" }
}
}
}})
$('#myupdategrid').kendoGrid({
dataSource:kendogridds,
height: 100,
columns:[{field:'data',title:'Data'},
{field:'value',title:'Value'}],
dataBound: onDataBound,
dataBinding: onDataBinding
})
I can see the grid being created but all the cells are empty. any clues why ?
You are right. There was something weird with the model. i don't think it likes data as a key in the data array. Once I changed that, everything started working fine. I hope this helps people.
this my code
var typeObject = {}
typeObject.name = properties
typeObject.value = map[properties]
gridArray.push(typeObject)
var kendogridds = new kendo.data.DataSource({
data:gridArray,
schema:{
model:{
fields:{
name:{ type:"string" },
value:{ type:"string" }
}
}
}})
console.log(kendogridds)
$('#myupdategrid').kendoGrid({autoBind:false,
dataSource:kendogridds,
columns: [{
field: "name",// create a column bound to the "name" field
title: "Data" // set its title to "Name"
}, {
field: "value",// create a column bound to the "age" field
title: "Value" // set its title to "Age"
}]
})
kendogridds.read()

Resources