React export Excel? - javascript

I want to give an array to the data part of the excel table. How can I do it ?
This is my code:
filteredData() {
for (const row of this.props.processes) {
const values = allverbisheaders.map((header) => {
return row[header];
});
this.state.CSVRows.push(values);
}
console.log(this.state.CSVRows[0]);
console.log(this.state.CSVRows[1]);
console.log(this.state.CSVRows[2]);
console.log(this.state.CSVRows[3]);
return this.state.CSVRows;
};
const VerbisSet = [
{
columns: [
{title: allverbisheaderstr[0], width: {wch: 27}},
{title: allverbisheaderstr[1], width: {wch: 20}},
{title: allverbisheaderstr[2], width: {wch: 33}},
{title: allverbisheaderstr[3], width: {wch: 30}},
{title: allverbisheaderstr[4], width: {wch: 30}},
{title: allverbisheaderstr[5], width: {wch: 30}},
{title: allverbisheaderstr[6], width: {wch: 30}},
{title: allverbisheaderstr[7], width: {wch: 30}},
],
data: [
[
this.state.CSVRows[0]
],
]
}
];
return (
<div>
<DropdownItem
onClick ={() => {this.filteredData()}}>
Process Listesi Kontrol
</DropdownItem>
<DropdownItem>
<ExcelFile element={<a>Verbis</a>}>
<ExcelSheet dataSet={VerbisSet} name="Verbis Data"/>
</ExcelFile>
</DropdownItem>
</div>
);
}
}
CSVRow is a matrix. And the first element is:
(8) ["Education", "Learning Information", "Education Status", "CONTRACT", "E", "E", "Employee", "EMAIL - HAND"]
I want to add this matrix to Excel table.
I pre-run the filteredData function and set the CSVRows matrix.

I am not exactly sure about the shape of your data, but I suspect the issue is due to the dimensions of the data.
From the library's document, the length of the data field should match the length of the columns field. However, your data field has a length of 1, while the length of columns is 8.
Try the following:
const VerbisSet = [
{
columns: [
{ title: allverbisheaderstr[0], width: { wch: 27 } },
{ title: allverbisheaderstr[1], width: { wch: 20 } },
{ title: allverbisheaderstr[2], width: { wch: 33 } },
{ title: allverbisheaderstr[3], width: { wch: 30 } },
{ title: allverbisheaderstr[4], width: { wch: 30 } },
{ title: allverbisheaderstr[5], width: { wch: 30 } },
{ title: allverbisheaderstr[6], width: { wch: 30 } },
{ title: allverbisheaderstr[7], width: { wch: 30 } },
],
data: [
// notice here, I removed one level of array nesting
this.state.CSVRows[0]
],
}
];
Or simply like this:
const VerbisSet = [
{
columns: [
{ title: allverbisheaderstr[0], width: { wch: 27 } },
{ title: allverbisheaderstr[1], width: { wch: 20 } },
{ title: allverbisheaderstr[2], width: { wch: 33 } },
{ title: allverbisheaderstr[3], width: { wch: 30 } },
{ title: allverbisheaderstr[4], width: { wch: 30 } },
{ title: allverbisheaderstr[5], width: { wch: 30 } },
{ title: allverbisheaderstr[6], width: { wch: 30 } },
{ title: allverbisheaderstr[7], width: { wch: 30 } },
],
data: this.state.CSVRows,
}
];

Related

Material-Table columns not resizable with more than 5 columns

I am displaying data using material-table. I have 19 columns to display and I want to set a fixed size for each column. Using width: 45% is not making any visual changes. I can't use whiteSpace: "nowrap" because that will only make the table longer and more difficult to use when some cells have large sentences. I have tried using width, cellStyle and headerStyle in all 19 of my columns but it made no difference.
Here are some of my columns and my table:
const columns = [
{ title: "Sizing ID", field: "SizingId" },
{ title: "Intake ID", field: "IntakeID" },
{ title: "FCRID", field: "FCRID" },
{ title: "Taxonomy ID", field: "TaxonomyId" },
{ title: "Domain", field: "Domain" },
{ title: "Experience", field: "Experience" },
{ title: "Product Line", field: "ProductLine" },
{ title: "Sizing Contact", field: "SizingContact" },
{ title: "Q1Cost", field: "Q1Cost" },
{ title: "Sizing Comments", field: "SizingComments" },
];
...
<MaterialTable
title="Sizing"
data={sizing.sizing}
columns={columns}
options={{
pageSize: 15,
pageSizeOptions: [15, 25, 50],
padding: "dense",
headerStyle: {
backgroundColor: "#0076CE",
color: "#e5e6e7",
fontFamily: "sans-serif",
fontSize: 12,
fontWeight: 600,
maxWidth: 200,
},
rowStyle: (data, index) => {
if (index % 2) {
return {
backgroundColor: "#EEEEEE",
fontSize: 12,
};
} else {
return { fontSize: 12 };
}
},
}}
/>
Just try to use Fixed columns with a large number of columns in the docs
https://material-table.com/#/docs/features/fixed-columns

Set width property array dynamically

I have a react table with group fields and resize-able columns.The columns are like below:
export const columns = [
{ title: 'Year Week',
dataIndex: 'year_week',
editable: false,
width: 60,
},
{
title: 'Actual Bank Amount',
dataIndex: 'actual_bank_amount',
width: 60,
editable: true
},
{
title: 'External Incomings',
key: 'external_incomings',
dataIndex: 'external_incomings',
className: "ext-in",
editable: true,
children: [
{ title: 'Rental Income/Leasing Income', width: 60, dataIndex: "ext_in_rental_income", key: "ext_in_rental_income", editable: true },
{ title: "Tax Refund", width: 60, dataIndex: "ext_in_tax_refund", key: "ext_in_tax_refund", editable: true },
{ title: "Dividends Income", width: 60, dataIndex: "ext_in_dividends_income", key: "ext_in_dividends_income", editable: true },
{ title: "Licence Income", width: 60, dataIndex: "ext_in_licence_income", key: "ext_in_licence_income", editable: true },
{ title: "Other Income", width: 60, dataIndex: "ext_in_other_income", key: "ext_in_other_income", editable: true },
]
}]
I am resizing the width in my reducer as below, but I am sure, we can do it in a far better way. Can someone please suggest a better way to do this. Below is my reducer code.
I simple words I want to set the width property dynamically in a function, where I have access to the dynamic "width" and the "dataIndex".
case 'SET_COLUMN_WIDTH':
const newColmuns = state.columns
Object.keys(newColmuns).map((key) => {
if (newColmuns[key].children) {
let Datakey = newColmuns[key].children.findIndex(item => item.dataIndex === action.payload.dataIndex)
if (Datakey > 0) {
newColmuns[key].children[Datakey].width = action.payload.size.width;
return
}
}
})
return {
...state,
columns: newColmuns
}
for(var col of columns)
{
if(col.children)
{
for(var child of col.children)
{
child.width = 123;
}
}
}

Kendo grid insert new row with custom class

This is how I insert new data to kendo grid, however i want my added row have a custom class, so I can style my new added row with different background color. How can I achieve this ? I searching all the doc can't find any related
var dataSource = $('#grid').data('kendoGrid').dataSource;
dataSource.insert(0, {
"name":"ABC",
"age": 99
});
In order to add a new class to each newly row you can use .addClass(). But, every time you move to the next/prev page or add other rows you need to add again the class....
In order to achieve that you can save in a global array a list of all newly added row uuid and on dataBound event reapply the class.
Fiddle here
var newUUID = [];
$("#grid").kendoGrid({
navigatable: true,
filterable: true,
pageable: {
pageSize: 5,
alwaysVisible: false,
pageSizes: [5, 10, 20, 100]
},
dataBound: function(e) {
$.each(newUUID, function(idx, ele) {
if ($(ele).length != 0) {
$(ele).addClass('newRow');
}
})
}
});
$('#btn').on('click', function(e) {
var dataSource = $('#grid').data('kendoGrid').dataSource;
var x = dataSource.insert(0, {
"name":"ABC",
"age": 99
});
newUUID.push("[data-uid='" + x.uid + "']");
$("[data-uid='" + x.uid + "']").addClass('newRow');
})
You can look-up the newly added row by its UID and add the class to the row.
I explored the solution on this blog: "Simple Row Coloring in a KendoUI Grid"
const sampleData = getSampleData();
$(document).ready(() => {
$("#example-grid-wrapper").kendoGrid({
dataSource: {
data: sampleData.data,
schema: {
model: {
fields: sampleData.fields
}
}
},
columns: sampleData.columns
});
setTimeout(insertNewRecordAfterOneSecond, 1000);
});
function insertNewRecordAfterOneSecond() {
// Insert data
let dataGrid = $('#example-grid-wrapper').data('kendoGrid');
dataGrid.dataSource.insert(0, { id: 1, name: "Sam", location: "B", color: "blue", status: 0 });
// Re-scan table and lookup newly added row.
dataGrid = $('#example-grid-wrapper').data('kendoGrid');
let dataView = dataGrid.dataSource.view();
for (let i = 0; i < dataView.length; i++) {
if (dataView[i].id === 1) {
dataGrid.table.find("tr[data-uid='" + dataView[i].uid + "']").addClass("highlighted-row");
}
}
}
function getSampleData() {
return {
data : [
{ id: 2, name: "Grant", location: "A", color: "green", status: 1 },
{ id: 3, name: "Vaughan", location: "B", color: "red", status: 0 },
{ id: 4, name: "David", location: "A", color: "orange", status: 1 }
],
fields : {
id: { type: "number" },
name: { type: "string" },
location: { type: "string" },
color: { type: "string" }
},
columns : [
{ field: "id", title: "ID", width: "10%" },
{ field: "name", title: "Name", width: "30%" },
{ field: "location", title: "Location", width: "30%" },
{ field: "color", title: "Color", width: "20%" },
{ field: "status", title: "Status", width: "10%" }
]
};
}
.highlighted-row {
background: #FF0; /* Higlight row yellow */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2019.2.619/js/kendo.all.min.js"></script>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2019.2.619/styles/kendo.common.min.css" />
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2019.2.619/styles/kendo.blueopal.min.css" />
<div id="example-grid-wrapper">
<div id="example-grid"></div>
</div>
Alternative
As suggested by gaetanoM.
const sampleData = getSampleData();
var insertedUidList = [];
$(document).ready(() => {
$("#example-grid").kendoGrid({
dataSource: {
data: sampleData.data,
schema: {
model: {
fields: sampleData.fields
}
}
},
columns: sampleData.columns,
// Suggested by gaetanoM
dataBound: function(e) {
$.each(insertedUidList, function(idx, uid) {
// Re-apply class to existing rows.
$(`tr[data-uid="${uid}"]`).addClass('highlighted-row');
});
}
});
// Insert two rows, one second apart.
insertRowsWithDelay([
{ id: 0, name: "Joseph", location: "A", color: "yellow", status: 1 },
{ id: 1, name: "Sam", location: "B", color: "blue", status: 0 },
], 1000)
});
function insertRowsWithDelay(data, delayBetween) {
if (data == null || data.length === 0) return;
setTimeout(() => {
insertNewRecord(data.pop());
insertRowsWithDelay(data, delayBetween);
}, 1000);
}
function insertNewRecord(record) {
record = $('#example-grid').data('kendoGrid').dataSource.insert(0, record);
insertedUidList.push(record.uid);
$(`[data-uid="${record.uid}"]`).addClass('highlighted-row');
}
function getSampleData() {
return {
data : [
{ id: 2, name: "Grant", location: "A", color: "green", status: 1 },
{ id: 3, name: "Vaughan", location: "B", color: "red", status: 0 },
{ id: 4, name: "David", location: "A", color: "orange", status: 1 }
],
fields : {
id: { type: "number" },
name: { type: "string" },
location: { type: "string" },
color: { type: "string" }
},
columns : [
{ field: "id", title: "ID", width: "10%" },
{ field: "name", title: "Name", width: "30%" },
{ field: "location", title: "Location", width: "30%" },
{ field: "color", title: "Color", width: "20%" },
{ field: "status", title: "Status", width: "10%" }
]
};
}
.highlighted-row {
background: #FF0; /* Higlight row yellow */
}
.highlighted-row.k-alt {
background: #DD0; /* Higlight row yellow */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2019.2.619/js/kendo.all.min.js"></script>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2019.2.619/styles/kendo.common.min.css" />
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2019.2.619/styles/kendo.blueopal.min.css" />
<div id="example-grid"></div>
You can try to create a databound function for the grid and then try this inside the function
function onDataBound(e) {
var dataSource = $("#GridName").data("kendoGrid").dataSource;
var data = dataSource.data();
$.each(data, function (index, rowItem) {
if (data.length > 0) {
var rows = e.sender.tbody.children();
var row = $(rows[index]);
if (data[index].name == "ABC" ) {
row.addClass("NameColor");
}
}
});
}
<style>
.NameColor {
background-color: black;
}
</style>
Like this you can try..

How to make inner object in object using recursive code in javascript

I have some object type data.
Each object have same key, children.
children can have another children.
const testColumns = {
label: '테스트 수',
width: 320,
children: [
{
label: '1-1111',
width: 160,
children: [
{
key: 'testCnt',
label: '2-3333',
width: 80,
},
{
key: 'exceptionCnt',
label: '2-4444',
width: 80,
children: [
{
key: 'allTestCnt',
label: '3-5555',
width: 80,
},
{
key: 'allExceptionCnt',
label: '3-6666',
width: 80,
},
]
}
]
}
]
};
I have to make other object from testColumns to rearranged object, returnColumns.
like this.
let returnColumns = [];
testColumns.map((obj)=>{
if(obj.children){
obj.children.map((child, firstChildIndex)=>{
returnColumns['children'] = [];
returnColumns.push({
property: child.key,
header: {
label: child.label,
},
props: {
style: {
width: child.width
}
});
if(child.children){
returnColumns[firstChildIndex]['children'] = [];
child.children.map((secondChild, secondChildIndex)=>{
returnColumns[firstChildIndex]['children'].push({
property: secondChild.key,
header: {
label: secondChild.label,
},
props: {
style: {
width: secondChild.width
}
});
})
}
});
}
})
I try to make above code to recursive function. like this.
function recursiveIteration(object, callback) {
for (let property in object) {
if (object.hasOwnProperty(property)) {
if (typeof object[property] == "object"){
recursiveIteration(object[property]);
// ...
// ...
}
}
}
}
But I don't know how work this.
Above code is sample. It's not perfect.
Here is jsfiddle link
Here is what I want result
const test = {
property: undefined,
header : {
label: 'TEST1'
},
props: {
style: {
width: 320,
}
},
children: [
{
property: 'test',
header : {
label: 'test'
},
props: {
style: {
width: 160,
}
},
},
{
property: undefined,
header : {
label: '2-4444'
},
props: {
style: {
width: 160,
}
},
children: [
{
property: 'allTestCnt',
header : {
label: '3-5555'
},
props: {
style: {
width: 80,
}
},
},
{
property: 'allExceptionCnt',
header : {
label: '3-6666'
},
props: {
style: {
width: 80,
}
},
}
]
}
]
};
}
You could use a recursive callback for mapping values of the array.
var testColumns = { label: '테스트 수', width: 320, children: [{ label: '1-1111', width: 160, children: [{ key: 'testCnt', label: '2-3333', width: 80, }, { key: 'exceptionCnt', label: '2-4444', width: 80, children: [{ key: 'allTestCnt', label: '3-5555', width: 80, }, { key: 'allExceptionCnt', label: '3-6666', width: 80, }, ] }] }] },
result = [testColumns].map(function iter(o) {
var temp = {
property: undefined,
header: { label: o.label },
props: { style: { width: o.width } }
};
if (o.children) {
temp.children = o.children.map(iter);
}
return temp;
})[0];
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

JQxTreeGrid is correctly rendered but data is not loaded from json source

Would appreciate some help tackling this please. So I have the following code to load up Json data into a Jquery grid.... jqxTreegrid. So far, The grid shows up but the data does not. In addition, debugger shows me no errors of any kind. So, I would appreciate any help to resolve this please.
$(document).ready(function () {
// prepare the data
var source =
{
dataType: "json",
dataFields: [
{ name: 'sid', type: 'string' },
{ name: 'id', type: 'string' },
{ name: 'position', type: 'string' },
{ name: 'created_at', type: 'string' },
{ name: 'created_meta', type: 'number' },
{ name: 'updated_at', type: 'string' },
{ name: 'updated_meta', type: 'string' },
{ name: 'meta_data', type: 'string' },
{ name: 'community_area_number', type: 'number' },
{ name: 'community_area_name', type: 'string' }
],
hierarchy:
{
root: 'sid'
},
id: 'sid',
//url: 'http://www.filedropper.com/employeesadv'
//url: 'gdiChicago/employeesadv.csv'
url: 'data.cityofchicago.org_Births-to-mothers-aged-15_19_kva-bt6k.json'
};
var dataAdapter = new $.jqx.dataAdapter(source);
$("#content").on('rowselect', function(event){
// event arguments
var args = event.args;
// row data
var rowData = args.row;
// row key
var rowKey = args.key;
console.log('RowSelect selected');
event.stopPropagation();
});
$("#content").on('bindingComplete', function(event)
{
$("#content").jqxTreeGrid('hideColumn', 'name');
console.log('Tree successfully loaded');
});
$("#content").on('beforeLoadComplete', function (records) {
var data = new Array();
// update the loaded records. Dynamically add EmployeeName and EmployeeID fields.
for (var i = 0; i < records.length; i++) {
var employee = records[i];
console.log(employee);
}
});
// create Tree Grid
$("#content").jqxTreeGrid(
{
width: 1000,
source: dataAdapter,
pageable: true,
columnsResize: true,
ready: function()
{
// expand row with 'EmployeeKey = 32'
$("#content").jqxTreeGrid('expandRow', 32);
},
columns: [
{ text: 'sid', dataField: 'sid', minWidth: 100, width: 300 },
{ text: 'id', dataField:'id', minWidth: 100, width: 300 },
{ text: 'position', dataField:'position', minWidth: 100, width: 300 },
{ text: 'created at', dataField: 'created_at' , minWidth: 100, width: 300 },
{ text: 'created meta', dataField: 'created_meta' , minWidth: 100, width: 300 },
{ text: 'updated at', dataField: 'updated_at', minWidth: 100, width: 300 },
{ text: 'updated meta', dataField:'updated_meta', minWidth: 100, width: 300 },
{ text: 'meta', dataField:'meta', minWidth: 100, width: 300 },
{ text: 'Community Area Number', dataField: 'community_area_number' , minWidth: 100, width: 300 },
{ text: 'community area name', dataField: 'community_area_name', minWidth: 100, width: 300 }
]
});
});
The json datasource I am trying to load can be obtained at this link Public Health Statistics - Births to mothers aged 15-19 years old in Chicago, by year, 1999-2009
Instead of using
hierarchy:
{
root: 'sid'
},
try using
hierarchy:
{
keyDataField: { name: 'sid' }
},

Categories

Resources