export large amount of data to excel crashes - c#

I have a kendo grid in my application and i have added export to excel button to that kendo grid .
My question here is if select the small amount of data in kendo grid and when click on export button everything is working fine
but the problem is if select the large amount of data more than 1000 rows then the web page will become crash and it showing "Aw, Snap" Error
my environment : C#, Jquery, Kendo Grid
I have this code in my js
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
tableToExcel("table2excel");
it works fine when the data is small . but if the data is large more than 1000 it crashes the browser
I heard that Chrome can only handle HREF's that are roughly 2 million characters long. So can i handle this using Blob object ? if yes can somebody let me know how to use blob object in my case ?
Please help to resolve this issue .

It exports all data and custom selection using checkbox as well.
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 Data Result",
rows: rows
}
]
});
kendo.saveAs({ dataURI: workbook.toDataURL(), fileName: "ExportedData" });
}

Related

Unable to create a company in Intercom

I'm using this code:
Authentication authentication = new Authentication("myAccessToken");
RestClientFactory restClientFactory = new RestClientFactory(authentication);
var _companyClient = new CompanyClient(restClientFactory);
var companyCustomAttributes = new Dictionary<string, object>()
{
{ "name", "TradingName" },
{ "company_id_str", "5432" },
{ "isoCode", "AU" },
{ "regionCode", "VIC" },
{ "isPropertyManagement", false },
{ "isSales", false },
{ "setupComplete", false },
{ "isSubscription", false },
{ "subscriptionSetupComplete", false },
{ "tradingName", "TradingName" },
{ "ofSMS", false },
{ "ofBankTransfer", false },
{ "ofCommercial", false },
{ "isEmailValidated", true },
{ "isLocked", false },
{ "isOutgoingEmailValidated", true },
{ "banks", "" },
{ "earlyAdopterProgram", false },
{ "propertyCount", 0 }
};
var company = new Company();
company.company_id = "5432";
company.custom_attributes = companyCustomAttributes;
var createdCompany = _companyClient.Create(company);
The createdCompany is not null:
But the company is not showing in the UI:
Why is the company not showing in the UI?
Intercom API version = 1.4
Intercom.Dotnet.Client version = 2.1.1
Github issue submitted:
https://github.com/intercom/intercom-dotnet/issues/158
The company won't show up if there are no users attached to it.

implement datatable js in Asp.Net API server side processing

I'm using datatable.js, I have table in view and API returns JSON results. I have lots of rows and i want to bind them by each page.Is there any way that datatable do it for me? I read lots of documentation but I didn't find anything useful for API
API Controller
public IHttpActionResult Get(int id)
{
return Ok(_context.Students.OrderBy(c => c.id).Skip((id - 1) * 10).Take(10).ToList());
}
Here is my table config
<script>$(document).ready(function () {
var pageindex = 1;
var table = $("#staff").DataTable({
"processing": true,
"serverSide": true,
ajax: {
url: "/Api/staffs",
dataSrc: "",
data: {
id: pageindex,
},
},
columns: [
{
data: "stf_FirstName",
},
{
data: "stf_LastName",
},
{
data: "stf_Code",
}
]
});
table.on('page', function () {
Currentpagenum();
});
function Currentpagenum() {
var info = table.page.info();
pageindex = (info.page + 1);
}
});</script>
If there are lots of rows than server side processing should be used
Try this :
HTML :
<table id="tblGrid" class="table display nowrap" style="width:100%">
</table>
JS :
function SetGrid() {
$('#tblGrid').DataTable({
"proccessing": true,
"serverSide": true,
// server side
"ajax": {
url: "/api/YourController/Method",
type: 'POST',
"data": {
Param1: Value1
}
},
// if client side
//data: YourList, // Js Array
columns: [
{ data: 'Id' },
{ data: 'Name', title: "Name" },
...
...
{ title: "Actions"},
],
"columnDefs": [
{ targets: 0, visible: false,},
],
"ordering": false,
"lengthChange": false,
"pageLength": 10,
"bDestroy": true,
"oLanguage": {
"sEmptyTable": "No Record Found"
},
});
}
Sample C# :
public object YourMethod(Param1 Value1)
{
var start = int.Parse(HttpContext.Current.Request.Form["start"]);
var result = new {
draw = HttpContext.Current.Request.Form["draw"],
recordsTotal = YourList.Count,
recordsFiltered = YourList.Count,
data = YourList.Skip(start).Take(10).ToList()
};
return result;
}

Change number format according to valueFormat column in kendo Grid

I have created dynamic kendo grid.In grid there is some columns which required formatting. I have one field "valueFormat" in database according that format I want to format other columns.
How to achieve above thing Please help.
link for sample grid
var data = [{
"Dept": "Dev",
"CalculateValue": 0 ,
"AcualValue": 341.917,
"ValueFormat": "#.###"
},
{
"Dept": "Dev",
"CalculateValue": 0,
"AcualValue": 5333.083,
"ValueFormat": "#.###"
},
{
"Dept": "Dev",
"CalculateValue":0 ,
"AcualValue": 8735.666,
"ValueFormat": "{0:c2}"
},
{
"Dept": "Dev",
"CalculateValue":0,
"AcualValue": 126.000,
"ValueFormat": "{0:c2}"
}];
var dateFields = [];
generateGrid(data)
function generateGrid(gridData) {
if ($(".k-header").length > 0) {
grid = $("#grid").data("kendoGrid");
grid.destroy();
$("#grid").empty();
}
$("#grid").kendoGrid({
toolbar: ["excel"],
excel: {
allPages: true,
filterable: true,
fileName: 'Aggregate Expenditure/Utilization Report_.xlsx'
},
dataSource: {
pageSize: 100,
schema: {
data: function () { return gridData; },
total: function () {
return gridData.length;
}
}
},
sortable: true,
filterable: true,
groupable: true,
pageable: true,
columns: generateModel(gridData[0]),
autoBind: true
});
$("#grid").data("kendoGrid").refresh();
}
function generateModel(gridData) {
var model = {};
model.id = "ID";
var fields = {};
for (var property in gridData) {
var propType = typeof gridData[property];
if (propType == "number") {
fields[property] = {
type: "number",
validation: {
required: true
}
};
} else if (propType == "boolean") {
fields[property] = {
type: "boolean",
validation: {
required: true
}
};
} else if (propType == "string") {
var parsedDate = kendo.parseDate(gridData[property]);
if (parsedDate) {
fields[property] = {
type: "date",
validation: {
required: true
}
};
dateFields.push(property);
} else {
fields[property] = {
validation: {
required: true
}
};
}
} else {
fields[property] = {
validation: {
required: true
}
};
}
}
model.fields = fields;
return model;
}
The Kendo grid's column formatting option won't work for you, because it applies the same formatting to all cells within a column, but you are going for different formatting in every row.
In that case you should specify a custom template for the ActualValue column. Inside that template you can use a formatting function to process your value. Since you are already using Kendo, you can take advantage of kendo.format(), like this:
template: "#: kendo.format(ValueFormat, AcualValue)#"
However, that does not work with all of your data, because some of the format strings are already wrapped in brackets and have an index like "{0:c2}", and others are not - "#.###". So you should create a function that makes sure they are consistent, before you pass them to kendo.format(). I've done this with fixValueFormatString(ValueFormat) below.
Here's a link to a working sample: http://jsbin.com/jejixediga/edit?js,console,output
And here's the code:
var data = [{
"Dept": "Dev",
"CalculateValue": 0 ,
"AcualValue": 341.917,
"ValueFormat": "#.###"
}, {
"Dept": "Dev",
"CalculateValue": 0,
"AcualValue": 5333.083,
"ValueFormat": "#.###"
}, {
"Dept": "Dev",
"CalculateValue":0 ,
"AcualValue": 8735.666,
"ValueFormat": "{0:c2}"
}, {
"Dept": "Dev",
"CalculateValue":0,
"AcualValue": 126.000,
"ValueFormat": "{0:c2}"
}];
var dateFields = [];
// Make sure all format strings are consistent
function fixValueFormatString(ValueFormat){
if(!ValueFormat.startsWith("{")){
ValueFormat = "{0:" + ValueFormat + "}";
}
return ValueFormat;
}
generateGrid(data)
function generateGrid(gridData) {
if ($(".k-header").length > 0) {
grid = $("#grid").data("kendoGrid");
grid.destroy();
$("#grid").empty();
}
$("#grid").kendoGrid({
toolbar: ["excel"],
excel: {
allPages: true,
filterable: true,
fileName: 'Aggregate Expenditure/Utilization Report_.xlsx'
},
dataSource: {
pageSize: 100,
schema: {
data: function () { return gridData; },
total: function () {
return gridData.length;
}
}
},
sortable: true,
filterable: true,
groupable: true,
pageable: true,
autoBind: true,
columns: [{
field: "Dept"
}, {
field: "CalculateValue",
}, {
template: "#: kendo.format(fixValueFormatString(ValueFormat), AcualValue)#",
field: "AcualValue"
}, {
field: "ValueFormat"
}]
});
$("#grid").data("kendoGrid").refresh();
}
function generateModel(gridData) {
var model = {};
model.id = "ID";
var fields = {};
for (var property in gridData) {
var propType = typeof gridData[property];
if (propType == "number") {
fields[property] = {
type: "number",
validation: {
required: true
}
};
} else if (propType == "boolean") {
fields[property] = {
type: "boolean",
validation: {
required: true
}
};
} else if (propType == "string") {
var parsedDate = kendo.parseDate(gridData[property]);
if (parsedDate) {
fields[property] = {
type: "date",
validation: {
required: true
}
};
dateFields.push(property);
} else {
fields[property] = {
validation: {
required: true
}
};
}
} else {
fields[property] = {
validation: {
required: true
}
};
}
}
model.fields = fields;
return model;
}
UPDATE - ASSIGN TEMPLATE TO DYNAMICALLY GENERATED COLUMNS
In response to OPs request for a solution that works with dynamic columns, here's the revised code (http://jsbin.com/jinowamosa/edit?js,console,output):
var data = [{
"Dept": "Dev",
"CalculateValue": 0 ,
"AcualValue": 341.917,
"ValueFormat": "#.###"
}, {
"Dept": "Dev",
"CalculateValue": 0,
"AcualValue": 5333.083,
"ValueFormat": "#.###"
}, {
"Dept": "Dev",
"CalculateValue":0 ,
"AcualValue": 8735.666,
"ValueFormat": "{0:c2}"
}, {
"Dept": "Dev",
"CalculateValue":0,
"AcualValue": 126.000,
"ValueFormat": "{0:c2}"
}];
var dateFields = [];
function fixValueFormatString(ValueFormat){
if(!ValueFormat.startsWith("{")){
ValueFormat = "{0:" + ValueFormat + "}";
}
return ValueFormat;
}
generateGrid(data)
function generateGrid(gridData) {
if ($(".k-header").length > 0) {
grid = $("#grid").data("kendoGrid");
grid.destroy();
$("#grid").empty();
}
$("#grid").kendoGrid({
toolbar: ["excel"],
excel: {
allPages: true,
filterable: true,
fileName: 'Aggregate Expenditure/Utilization Report_.xlsx'
},
dataSource: {
pageSize: 100,
schema: {
data: function () { return gridData; },
total: function () {
return gridData.length;
}
}
},
sortable: true,
filterable: true,
groupable: true,
pageable: true,
autoBind: true,
columns: generateColumns(gridData[0])
});
$("#grid").data("kendoGrid").refresh();
}
function generateColumns(gridData) {
var fields = {};
var columns = [];
for (var property in gridData) {
var propType = typeof gridData[property];
if (propType == "number") {
fields[property] = {
type: "number",
validation: {
required: true
}
};
} else if (propType == "boolean") {
fields[property] = {
type: "boolean",
validation: {
required: true
}
};
} else if (propType == "string") {
var parsedDate = kendo.parseDate(gridData[property]);
if (parsedDate) {
fields[property] = {
type: "date",
validation: {
required: true
}
};
dateFields.push(property);
} else {
fields[property] = {
validation: {
required: true
}
};
}
} else {
fields[property] = {
validation: {
required: true
}
};
}
}
for (var field in fields) {
if(field == 'AcualValue'){
columns.push({ field: field, template: "#: kendo.format(fixValueFormatString(ValueFormat), AcualValue)#" });
} else {
columns.push({ field: field });
}
}
return columns;
}
Hope this helps!

Datatables.Net - not populating from JSON data

I am working with a Datatables.Net plug into an internal web application to my company.
The issue Im facing is in the variable JSON, I can see that I have returned a JSON response, and it is valid according to JSONLint, but I cannot get the information out of the JSON array into my tables despite following all the examples on Datatables and searching their help site.
please see my code and let me know why this isn't populating the tables.
function populateTable(json, tableId) {
var id = 'table_' + tableId;
console.log("Columns In");
//console.log("table id: " + id + " JSON Response: " + json);
try {
var table = $('#' + id).DataTable({
"data": json.d,
"deferRender": true,
"columns:": [
{ "data ": "CaseHandlerStaffNumber" },
{ "data ": "RiskProfileText" },
{ "data ": "AssignedCheckerStaffNumber" },
{ "data ": "FeedbackUserStaffNumber" },
{ "data ": "ComplaintRef" },
{ "data ": "ChildComplaintRef" },
{ "data ": "CaseTypeText" },
{ "data ": "CheckGrade" }
]
});
} catch (e) {
}
try {
table.columns().every(function () {
var that = this;
$('input', this.footer()).on('keyup change', function () {
if (that.search() !== this.value) {
that
.search(this.value)
.draw();
}
});
});
} catch (e) {
console.log("Error detected: " + e);
console.log(e);
}
}
-- edit --
this is an example of my JSON data.
{
"data": [{
"CaseHandlerStaffNumber": "12345678",
"RiskProfileText": "Low Risk FOS",
"AssignedCheckerStaffNumber": "77665544",
"FeedbackUserStaffNumber": null,
"ComplaintRef": "999999",
"ChildComplaintRef": "2333",
"CaseTypeText": "FOS Submission",
"CheckGrade": "Ungraded"
}]
}
also, this is how I am producing the JSON
[System.Web.Services.WebMethod()]
public static object GetDataTables(string checkId, int userId)
{
List<string> listOfColumnns = new List<string>();
listOfColumnns.Add("CaseHandlerStaffNumber");
listOfColumnns.Add("RiskProfileText");
listOfColumnns.Add("AssignedCheckerStaffNumber");
listOfColumnns.Add("FeedbackUserStaffNumber");
listOfColumnns.Add("ComplaintRef");
listOfColumnns.Add("ChildComplaintRef");
listOfColumnns.Add("CaseTypeText");
listOfColumnns.Add("CheckGrade");
int checkStatusId = Convert.ToInt32(checkId.Replace("hidJson_tbl_", ""));
TeamChecks tc = new TeamChecks();
DataTable dtMc = default(DataTable);
dtMc = tc.Get_DatatableFor_GridView(userId, checkStatusId);
DataTable dt = new DataTable();
foreach (void colName_loopVariable in listOfColumnns) {
colName = colName_loopVariable;
dt.Columns.Add(string.Format("{0}", colName));
}
foreach (void row_loopVariable in dtMc.Rows) {
row = row_loopVariable;
dt.Rows.Add(row("CaseHandlerStaffNumber"), row("RiskProfileText"), row("AssignedCheckerStaffNumber"), row("FeedbackUserStaffNumber"), row("ComplaintRef"), row("ChildComplaintRef"), row("CaseTypeText"), row("CheckGrade"));
}
string jsonResult = null;
jsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(dt);
jsonResult = jsonResult.Replace("[{", "{\"data\" :[{").Replace("}]", "}]}");
return jsonResult;
}
First, make sure you remove extra space at the end of "data" property, e.g.
{ "data": "caseHandlerStaffNumber" },
If your data is in a form of array of objects you need to use "title" property as defined here https://datatables.net/examples/data_sources/js_array.html e.g.
$('#example').DataTable( {
data: dataSet,
columns: [
{ title: "Name" },
{ title: "Position" },
{ title: "Office" },
{ title: "Extn." },
{ title: "Start date" },
{ title: "Salary" }
]
} );
If you're using nuget package, it internally uses Json.NET serializer with an option to lower case first letter of the data set. So, you just need to use lower case when specifying data as follows:
{ "data": "caseHandlerStaffNumber" },
{ "data": "riskProfileText" },
{ "data": "assignedCheckerStaffNumber" },
{ "data": "feedbackUserStaffNumber" },
{ "data": "complaintRef" },
{ "data": "childComplaintRef" },
{ "data": "caseTypeText" },
{ "data": "checkGrade" }

Export to Excel directly from datasource with sorting and grouping for Kendo UI

I am trying to export data to excel file directly from datasource, I am able to export it to excel but the problem is the data are not sorted the way I want it to be nor group in the way I want it to be.
No matter what I do, the output is not sorted the way I want it to be, it is just as same as the way the data is retrieved from datasource.
Sample Input data:
|Celine|29|Female|
|Kian|25|Male|
|Juan|40|Male|
|Satia|25|Female|
|Kulim|50|Male|
|Liz|15|Female|
Sample Output in excel:
|Liz|15|Female|
|Satia|25|Female|
|Celine|29|Female|
|Kian|25|Male|
|Juan|40|Male|
|Kulim|50|Male|
Here is a snippet of code I used:
$(".export-excel").click(function () {
var from = new Date($("input#startDate").val()), to = new Date($("input#endDate").val());
var ds = new kendo.data.DataSource({
type: "odata",
transport: {
read: {
url: webApiUrl +
"/data/getdata(startDateString='" +
(from.getFullYear() + "-" + (from.getMonth() + 1) + "-" + from.getDate()) +
"', endDateString='" + (to.getFullYear() + "-" + (to.getMonth() + 1) + "-" + to.getDate()) + "')",
dataType: "json"
},
parameterMap: function (options, data) {
var paramMap = kendo.data.transports.odata.parameterMap(options);
var d = kendo.data.transports.odata.parameterMap(data);
delete paramMap.$inlinecount;
delete paramMap.$format;
paramMap.$count = true;
return paramMap;
}
},
schema: {
data: function (data) {
return data.value;
},
total: function (data) {
return data['odata.count'];
},
errors: function (data) {
},
model: {
fields: {
Name: { type: "string" },
Age: { type: "string" },
Gender: {type:"string"}
}
},
group: {
field: "Gender"
}
},
sort: {
field: "Gender",
dir: "asc"
},
sortable: true,
pageable: true,
groupable: true,
filterable: true,
});
ds.fetch(function () {
var data = this.data();
for (var i = 0; i < data.length; i++) {
rows.push({
cells: [
{ value: data[i].Name },
{ value: data[i].Age},
{ value: data[i].Gender}
]
})
}
var workbook = new kendo.ooxml.Workbook({
sheets: [
{
columns: [
// Column settings (width)
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true }
],
title: "Peaple_Report"
}
]
});
//save the file as Excel file with extension xlsx
kendo.saveAs({ dataURI: workbook.toDataURL(), fileName: "Test.xlsx" });
});
});
Thank you in advanced.
.data() method holds the pristine data when not sorted or filtered ...
when you have applied any filter or sorting or grouping or paging ... you should read the data from .view() method ... that will give you the sorted/filtered data you are looking for ...
here is the documentation of .view() method - http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#methods-view

Categories

Resources