I am able to read Excel file I need to read xls file col-wise, read data in every column and convert it to JSON.
How to read xls file col by col?
Getting trouble while fetching just first column data from xlsx file with vuejs
How to get particular column data from xlsx file with Vue js, anyone/?
i'm new to Vue js.
here, is the code that i used.
<template>
<div>
<p v-if="err!==''">{{err}}</p> <!-- Used to display errors -->
<table v-if="content!==''"> <!-- Set center,Do not display if no content is obtained -->
<!-- <tr>
<th v-for="h in content[0]" :key="h.id">{{h}}</th>
</tr> Cycle read data and display -->
<tr v-for="row in content.slice(0,)" :key=row.id>
<td v-for="item in row" :key=item.id>{{item}}</td>
</tr>
</table>
</div>
</template>
<script>
import axios from 'axios'
import XLSX from 'xlsx'
export default {
name: "App",
data(){
return {
content: '', //Initialization data
err: ''
}
},
created() {
var url = "/filw.csv" //Files placed in the public directory can be accessed directly
axios.get(url, {responseType:'arraybuffer'})
.then((res) => {
var data = new Uint8Array(res.data)
var wb = XLSX.read(data, {type:"array"})
const firstSheetName = wb.SheetNames[0]
const sheets = wb.Sheets[firstSheetName]
// const results = XLSX.utils.sheet_to_json(sheets)
// this.content = results
this.content = this.getColumnData(sheets)
}).catch( err =>{
this.err = err
})
},
methods: {
getColumnData(sheet) {
const ColData = []
const range = XLSX.utils.decode_range(sheet['!refs'])
let C
const R = range.s.r
/* start in the first row */
for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */
const cell = sheet[XLSX.utils.encode_col({ c: C, r: R })]
ColData.push(cell)
}
return ColData
}
}
}
</script>
<style>
</style>
ANyone who know, help would be much appreciated ;-)
You can convert the data to json and then read the result, like this:
created() {
var url = "/test.xlsx"
axios.get(url, {responseType:'arraybuffer'})
.then((res) => {
var data = new Uint8Array(res.data)
var wb = XLSX.read(data, {type:"array"})
const firstSheetName = wb.SheetNames[0]
const first_worksheet = wb.Sheets[firstSheetName]
// convert to json
const file_data = XLSX.utils.sheet_to_json(first_worksheet, { header: 1 });
// first column first row value
console.log(file_data[0][0])
})
.catch( err =>{this.err = err})
},
Related
app.component.html
This is my app.component file where i show my chart
<div style="display: block;">
<canvas baseChart width="400" height="400"
[datasets]="lineChartData"
[labels]="lineChartLabels"
[options]="lineChartOptions"
[colors]="lineChartColors"
[legend]="lineChartLegend"
[chartType]="lineChartType">
</canvas>
</div>
app.component.ts
My ts file where the logic impleneted i have issue there i am not know how to perform logic to show the data i have issue how to create method in it which will call in the app.component.html file
constructor(private chartService: ChartServiceService) { }
ngOnInit(): void {
this.getlinechart();
}
getlinechart(){
this.chartService.getLineChart().subscribe(res => {
this.linechart = res;
console.log(res);
let lincechartData = res.list[0].data;
let lincechartLabels = res.list[0].graphlabels;
public lineChartData:any = this.lincechartData;
**I,m facing issue here above to create method to store the
data and used in html compiler give the error this ,'
expected.ts(1005)
Cannot find name 'lineChartData'**
});
}
app.service.ts
This is service file which getting the data from the backend nodejs api
getLineChart(){
return this.httpClient.get<any>
('http://localhost:3000/api/chart/line')
.pipe(
map(result => result)
)
}
If i undestand correctly you are trying to read data from a database and put it on a chart. I did something similar, but i had a bit different approach:
HTML:
<canvas id="myChart" width="300" height="100"></canvas> <br/>
Chart config:
var config = {
type: 'line',
data: { datasets: [] }, // trend data goes here
options: {
scales: {
xAxis: { // x axis
type: 'time',
}
},
},
}
New chart:
function newChart() {
config.data.datasets = []; // reset data
populateTrend(config); // populate chart
if (window.hasOwnProperty("graph")) { // destroy previous chart
if (typeof window.graph.resetZoom !== "undefined") { // if you have a zoom plugin
window.graph.resetZoom();
}
window.graph.destroy();
}
let ctx = document.getElementById('myChart').getContext('2d'); // canvas
window.graph = new Chart(ctx, config); // make the chart
}
populate trend:
function populateTrend (config) {
// data sets and scales
let datasets = config.data.datasets, scales = config.options.scales;
let log = data; // this is where you read from your database
let dataset = { // add some data here
data: [],
label: log.description,
fill: false,
radius: 0,
unit: log.unit,
pointType: log.pointType,
yAxisID: log.unit, // y axis
};
// this is where the real data goes
// you should push the data in a loop
dataset.data.push({
"x": something.getTime(),
"y": null,
"ymin": null,
"ymax": null,
});
datasets.push(dataset); // add data set to config
}
I'm building a trading application and using node on the server side and react on client side.The current issue which I'm facing is regarding react performance on very frequents updates.
My process is describe as below.
The most common case I have is two tables displaying option data call and put. Each table have min of two rows and max of 8, so in total we'll have max 16 rows at single time. Each row can have up to 30 columns.
For updating I'm using a socket connection. Whenever a simple change occur in any of option column occurs an event emits from socket server which I'll be listening on client side.
After getting the data on client side via socket I can search for the specific row and column that where to update the data then re build the whole data of all 16 rows using the old data and new data and then dispatch the action... this updates occurs very frequently like 100s of 1000s of updates per millisecond and because of which whole table got re rendered and causing my app slow down.
I'm using redux to manage state in my react application
Here is an example with pure components no problem updating about 100 times a second:
const { useState, memo, useEffect, useRef } = React;
const COLUMS = 31;
const ITEM_COUNT = COLUMS * COLUMS;
const TIMER = 10;
const COLORS = ['red', 'green', 'blue'];
const nextColor = ((current) => () =>
COLORS[++current % COLORS.length])(0);
const next = ((num) => () => ++num % ITEM_COUNT)(-1);
const Item = memo(function Item({ color }) {
return (
<td
style={{
border: '1px solid black',
minWidth: '20px',
minHeight: '20px',
backgroundColor: color,
transitionDuration: '2s',
transitionTimingFunction: 'ease-out',
transitionProperty: 'color, background-color',
}}
>
</td>
);
});
const Row = memo(function Row({ items }) {
return (
<tr>
{items.map((item) => (
<Item key={item.id} color={item.color} />
))}
</tr>
);
});
const App = () => {
const r = useRef(0);
r.current++;
const [data, setData] = useState(
new Array(ITEM_COUNT)
.fill('')
.map((_, id) => ({ id, color: 'red' }))
.reduce((result, item, index) => {
if (index % COLUMS === 0) {
result.push([]);
}
result[result.length - 1].push(item);
return result;
}, [])
);
useEffect(() => {
const i = setInterval(
() =>
setData((data) => {
const change = next(), //id to change
color = nextColor(); //new value for color
return data.map(
(items) =>
//do not update items if id is not in this row
items.find(({ id }) => id === change)
? //update the one item that has id of change
items.map(
(item) =>
item.id === change
? { ...item, color } //change the color
: item //return the item unchanged
)
: items //id is not in this row return items unchanged
);
}),
TIMER
);
return () => clearInterval(i);
}, []);
return (
<div>
<h1>rendered: {r.current}</h1>
<table>
<tbody>
{data.map((items, index) => (
<Row key={index} items={items} />
))}
</tbody>
</table>
</div>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
I don't know why you're rerendering your components so frequently, but you can try throttling the updates to your redux store. This way you'll show all the latest data to your user without overburdening the CPU.
You can use throttle-debounce package to throttle your socket callback. Subsequent calls to the throttled function will only succeed if a given interval has been passed since the last call.
am trying to format displayed value in an angular table
this is my table right now
instead of showing the link am trying to format the displayed content link
instead of https://www.udemy.com/course/amazon-alexa-101-publishing-alexa-skills-without-coding/
am trying to show [amazon alexa 101 publishing alexa skills without coding]
i have tried in nodejs
var url = require('url');
var adr ='https://www.udemy.com/course/technology-strategy-success/?couponCode=05DIwC2320';
var q = url.parse(adr, true);
var data = q.pathname.replace("/course/", '');
var output = data.replace("/", '');
console.log(output);
this is my ts file
import {Component, OnDestroy, OnInit} from '#angular/core';
import {ApiService} from '../../services/api.service';
#Component({
selector: 'app-data',
templateUrl: './data.component.html',
styleUrls: ['./data.component.css']
})
export class DataComponent implements OnInit{
udemydata = [];
constructor(private apiService: ApiService) {
}
ngOnInit() {
this.apiService.getCoupen().subscribe((data: any[]) => {
this.udemydata = data;
console.log(data);
},
error => {
console.log('err', error);
}
);
}
}
this is my component.html file
<table datatable [dtOptions]="dtOptions" class="table align-items-center table-flush">
<thead>
<tr>
<th scope="col">S.No</th>
<th scope="col">course</th>
<th scope="col">Link</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let data of udemydata; let i = index;">
<td>{{i+1}}</td>
<td>{{data["courseidhref"]}}</td>
<td><a href ="{{data['courseidhref']}}" target="_blank"><button class="btn btn-icon btn-3 btn-primary" type="button">
<span class="btn-inner--icon"><i class="ni ni-send"></i></span>
<span class="btn-inner--text">Enroll Now</span>
</button></a></td>
</tbody>
</table>
First of all, note that Angular runs in user's browser, so you want to use the URL class, instead of Node's url module, as that is only available in Node runtime.
The, we can break down the process into a few steps:
const url = 'https://www.udemy.com/course/technology-strategy-success/?couponCode=05DIwC2320';
// first, convert to URL class so that it can do the parsing for us.
const parsedUrl = new URL(url);
// we want to ignore the host and query string, so we only need the pathname, as you have yourself discovered.
const pathName = parsedUrl.pathname;
// then, let's split the pathname on any "/" characters.
const urlParts = pathName.split('/');
// this produces some empty strings, so let's get rid of them
const nonEmptyParts = urlParts.filter(x => x !== '');
// now we are left with proper url parts.
// In our case: [ "course", "technology-strategy-success" ]
// Assuming that the last element is always the course name:
const coursePart = nonEmptyParts.pop(); // or, nonEmptyParts[nonEmptyParts.length - 1]
// Finally, let's get rid of the hyphens, replacing them with spaces.
// The regex has two parts:
// 1. /-/ stands for match hyphens
// 2. g stands for "global" - we want to replace ALL hyphens, not just the first one
const courseName = coursePart.replace(/-/g, ' ');
If you want to add a bit more sugar, you could also change the first letter of the course title to be a capital.
const title = courseName[0].toUpperCase() + courseName.slice(1);
// Technology strategy success
If you want to capitalize every word:
const title = courseName.split(' ')
.map(word => word[0].toUpperCase() + word.slice(1))
.join(' ');
// Technology Strategy Success
Now, to show it in Angular you could go about it in a few ways:
After you receive the data from your service, convert it so that the data also has the course title.
Create a method in your component that converts url to course title and call it in the template: <td>{{convertHrefToTitle(data.courseidhref)}}</td>
Create a courseTitle Pipe that transforms hrefs to titles. You would use it like so:
<td>{{data.courseidhref | courseTitle}}</td>
Option 1 is fairly simple. When we get the data, we transform it once.
Option 2 is very simple too, but the function will run VERY frequently, on every change detection cycle. This might affect performance if used without thinking.
Option 3 is slightly more complicated, but it will NOT run on change detection cycle unless the href itself has changed. Read more about pipes ion official docs.
Here's an example of how to use Option 1:
Given interfaces
interface OriginalData {
courseidhref: string;
}
interface TransformedData {
courseidhref: string;
title: string;
}
transformData(data: OriginalData ): TransformedData {
return {...data, title: this.hrefToTitle(data.courseidhref)}
}
hrefToTitle(href: string): string {
// paste the solution from above into here
}
ngOnInit() {
this.apiService.getCoupen().subscribe((data: any[]) => {
const transformedData = data.map(course => this.transformData(course));
this.udemydata = transformedData;
console.log(data, transformedData);
},
error => {
console.log('err', error);
}
);
}
Finally, in your template you can do
<td>{{data.title}}</td>
<td><a href ="{{data.courseidhref}}" target="_blank">...
I'm using moment.js and jquery datatables. Specifically, I have a a list of cells that all contain a Unix Timestamp.
What I'd like to do is convert this timestamp to the user's localized time (based on his/her timezone).
I am able to get the timezone to localize, but it only works for the first group of paginated results in my table...if I navigate to another page, the timestamp still shows up as the raw unix value.
I've made a JS fiddle to illustrate.
Could someone kindly let me know 1) if there's a better way to do what I'm doing 2) how I can localize my times even after actions like a) searching the table 2) sorting the table 3) paginating the table?
Huge thanks in advance!
My JS:
// Do Datatables
$('.my-datatable').DataTable({
"order": [[ 1, 'desc' ],],
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [ 0 ] }
]
});
// Loop through class to localize unix time based on user's time zone
function localizeTime(){
$( ".localize_time" ).each(function() {
if (typeof moment !== 'undefined' && $.isFunction(moment)) {
var userMomentTz = moment().format("Z");
var userTimeZone = userMomentTz.replace(":", "");
var elementSiteUnixTimeText = $(this).find('.localize_time_unix').text();
var elementSiteUnixTimeVal = parseInt(elementSiteUnixTimeText.trim());
if (userTimeZone.substring(0, 1) == "-") {
var userTimeZoneHr = parseInt(userTimeZone.substring(1,3));
var userTimeZoneMin = parseInt(userTimeZone.slice(-2));
var userTimeOffset = (userTimeZoneHr + '.' + (userTimeZoneMin/60))*(-1);
} else {
var userTimeZoneHr = parseInt(userTimeZone.substring(0,2));
var userTimeZoneMin = parseInt(userTimeZone.slice(-2));
var userTimeOffset = userTimeZoneHr + '.' + (userTimeZoneMin/60);
}
var momentDateUserOffset = moment.unix(elementSiteUnixTimeVal).utcOffset(userTimeOffset);
var momentDateFormattedOffset = moment(momentDateUserOffset).format('ddd, D MMM YYYY, h:mm A');
$(this).find('.localize_time_display').text(momentDateFormattedOffset);
};
});
};
// Run time localization function
if ( $( ".localize_time" ).length ) {
localizeTime()
};
My HTML
<table class="my-datatable">
<thead>
<tr>
<th>Time</th>
<th>Stuff</th>
</tr>
</thead>
<tbody>
<tr>
<td>Stuff</td>
<td>
<span class="localize_time">
<span class="localize_time_unix">UNIX Time n++</span>
<span class="localize_time_display"></span>
</span>
</td>
</tr>
</tbody>
</table>
Ok, well fortunately this was easier than I thought using 'data rendering'
Working JS Fiddle
Hope this helps someone!
My updated JS
// Do Datatables
$('.my-datatable').DataTable( {
"order": [[ 1, 'desc' ],],
"columnDefs": [{
"targets": 1,
"render": function (data, type, full, meta) {
if (typeof moment !== 'undefined' && $.isFunction(moment)) {
var userMomentTz = moment().format("Z");
var userTimeZone = userMomentTz.replace(":", "");
var elementSiteUnixTimeText = data;
var elementSiteUnixTimeVal = parseInt(elementSiteUnixTimeText.trim());
if (userTimeZone.substring(0, 1) == "-") {
var userTimeZoneHr = parseInt(userTimeZone.substring(1,3));
var userTimeZoneMin = parseInt(userTimeZone.slice(-2));
var userTimeOffset = (userTimeZoneHr + '.' + (userTimeZoneMin/60))*(-1);
} else {
var userTimeZoneHr = parseInt(userTimeZone.substring(0,2));
var userTimeZoneMin = parseInt(userTimeZone.slice(-2));
var userTimeOffset = userTimeZoneHr + '.' + (userTimeZoneMin/60);
}
var momentDateUserOffset = moment.unix(elementSiteUnixTimeVal).utcOffset(userTimeOffset);
var momentDateFormattedOffset = moment(momentDateUserOffset).format('ddd, D MMM YYYY, h:mm A');
$(this).find('.localize_time_display').text(momentDateFormattedOffset);
return momentDateFormattedOffset;
};
}
}]
} );
I have a kendo mvc grid and I am trying to export data to excel.
This is my .chhtml.
<div class="panel-body table-responsive">
#{
var gridBuilder = CodeTaskKendoGrid.CreateTaskGrid(Model.TaskOverviewList, Model.ViewableExtraFields, this.Html, Model.Configuration);
gridBuilder.ToolBar(tools => tools.Excel())
.Excel(excel => excel
.AllPages(true)
.ProxyURL(Url.Action("Excel_Export_Save", "Task"))
);
}
#gridBuilder.ClientDetailTemplateId("client-template")
</div>
<script id="client-template" type="text/x-kendo-template">
# if (SubTasks != null && SubTasks.length > 0) { #
<text>
<table class="adra-kendo-table">
# var j = SubTasks.length; #
# for(var i = 0; i < j; i++) { #
# var ownerName= SubTasks[i].OwnerName; #
# var taskStatusId= SubTasks[i].TaskStatusId; #
# var taskId = SubTasks[i].Id; #
# var periodId = SubTasks[i].PeriodId; #
# var teamId = SubTasks[i].TeamId; #
<tr>
<td>#: SubTasks[i].Id #</td>
<td>#: SubTasks[i].Name #</td>
<td class="# #CodeTaskKendoGrid.OwnerClass("ownerName") #"># #CodeTaskKendoGrid.OwnerName("ownerName") #</td>
<td>#: SubTasks[i].TaskStatus #</td>
<td>#: SubTasks[i].ApprovalStatus #</td>
<td><a class="btn btn-warning btn-xs" href="/Task/EditTask?taskId=#=taskId#&periodId=#=periodId#&teamId=#=teamId#" type="button">Edit</a></td>
</tr>
# } #
</table>
</text>
# } #
And this is where I generate the grid (this is another .cshtml file and I am using this to generate t the grid. I call the method in this file from the above file)
public static GridBuilder<DtoTaskExtended> CreateTaskGrid(IEnumerable<DtoTaskExtended> taskList, IEnumerable<DtoExtraField> viewableExtraFields , System.Web.Mvc.HtmlHelper htmlHelper, TaskGridConfig gridConfig)
{
ExtraFieldConfigs = viewableExtraFields;
Helper = htmlHelper;
GridConfig = gridConfig;
var retObj = Helper.Kendo().Grid(taskList)
.Name("AdraKendoGrid")
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("GetTaskResult", "Task"))
)
.Columns(ColumnsConfigurator)
.Groupable(gr => gr.Messages(message => message.Empty(Strings.kendoGroupMsg)))
.Pageable(pager => pager.PageSizes(new int[] { 15, 50, 100, 500 })
.Info(true)
.Messages(message => message.Display("{0} - {1} " + Strings.of + "{2} " + Strings.items))
.Messages(message => message.ItemsPerPage(Strings.itemsPerPage))
.Messages(message => message.Empty(Strings.noItemsToDisplay)))
.Resizable(r => r.Columns(true))
.Sortable()
.Reorderable(reorder => reorder.Columns(true))
.Resizable(r => r.Columns(true))
.ColumnMenu();
return retObj;
}
And finally, this is my controller action supposed to be called from the excel import button.
[HttpPost]
public ActionResult Excel_Export_Save(string contentType, string base64, string fileName)
{
var fileContents = Convert.FromBase64String(base64);
return File(fileContents, contentType, fileName);
}
But this controller action does not even get called when click the Excel Import button in the grid.
What am I doing wrong? Any suggestion is appreciated.
Thank you.
After specifying this
.ToolBar(tools => tools.Excel())
.Excel(excel => excel
.AllPages(true)
.ProxyURL(Url.Action("Excel_Export_Save", "Task"))
);
and creating relevant Action Methods, should I do anything more?
I have tried lot of examples, but my button (Export to Excel) button does not do anything. I have imported the jsZip.js file (as specified in Kendo Demo) as well. I am following the below examples.
http://demos.telerik.com/aspnet-mvc/grid/excel-export
http://docs.telerik.com/kendo-ui/aspnet-mvc/helpers/grid/excel-export
Any kind of help is appreciated. I am stucked here.
One solutions is:
<script src="//cdnjs.cloudflare.com/ajax/libs/jszip/2.4.0/jszip.min.js"></script>
The issue was with the Kendo MVC version I was using. Excel export is supported from the Kendo 2014 Q3 (2014.3.1119) version.