Export Json data to an excel file using Angular 4 - json

I have an Array List of objects. I want to export those data to an Excel file (.xlsx or .xls).
The template of the Excel file is also given. What needs to be done is only mapping to an existing Excel file. The Excel file is located in the Angular project itself. How can I achieve this using Angular 4.
[
{
"name": "Roshan",
"age": "35"
},
{
"name": "Ritika",
"age": "29"
}
]
The above data should be map to an Excel of having column names are Employee_Name and Employee_age.

try xlsx package
install xlsx to your project
npm install xlsx --save
import { Injectable } from '#angular/core';
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';
const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
const EXCEL_EXTENSION = '.xlsx';
#Injectable()
export class ExcelExportService {
constructor() { }
public exportAsExcelFile(json: any[], excelFileName: string): void {
const worksheet: XLSX.WorkSheet = XLSX.utils.aoa_to_sheet(json);
const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer' });
this.saveAsExcelFile(excelBuffer, excelFileName);
}
private saveAsExcelFile(buffer: any, fileName: string): void {
const data: Blob = new Blob([buffer], {
type: EXCEL_TYPE
});
FileSaver.saveAs(data, fileName + EXCEL_EXTENSION);
}
}
export class AppComponent {
name = 'Angular 6';
data: any = [{
eid: 'e101',
ename: 'ravi',
esal: 1000
},
{
eid: 'e102',
ename: 'ram',
esal: 2000
},
{
eid: 'e103',
ename: 'rajesh',
esal: 3000
}];
constructor(private excelService:ExcelExportService ){
}
exportAsXLSX():void {
this.excelService.exportAsExcelFile(this.data, 'sample');
}
}

You can export multiple sheets to an excel file using this code. First I created a service file and created a method exportAsExcelFile() This method code is included below. fileInfo is the object that I am including in the code section.
#Injectable({
providedIn: 'root'
})
export class ExcelExportServiceService {
constructor() { }
public exportAsExcelFile(fileInfo: ExportFileInfo): void {
const workbook: XLSX.WorkBook = XLSX.utils.book_new();
fileInfo.templates.forEach((x)=>{
XLSX.utils.book_append_sheet(workbook,
XLSX.utils.json_to_sheet(x.data), x.sheetName);
});
XLSX.writeFile(
wb,
`${fileInfo.fileName}`
);
}
export interface ExportFileInfo{
fileName:string;
templates:ExportTemplateInfo[];
}
export interface ExportTemplateInfo{
data:any;
sheetName:string;
}
constructor(private exportService: ExcelExportServiceService) {}
excelFileExportFromJson(){
let data:any[]=[];
this.analysisDrugList.forEach(x=>{
data.push({
'NDC-9':x.ndc.substring(0,9),
'Canister':x.drawerType==='Smart'?'SMART':x.canisterLocation,
'Drug Name':x.name,
'Strength':x.strength,
'Manufacturer':x.manufacturer,
'NDC-11':x.ndc,
'CustomerNDC':x.customerDrugNdc,
'CItem#':x.atpCanisterNumber,
})
})
this.fileInfo={
fileName: `test_file_name.xlsx`,
templates:[{
data:data,
sheetName:`test_sheet`
}]}
this.exportService.exportAsExcelFile(this.fileInfo);
}

Related

How to Search a particular array from a json object in a json file in angular?

I want to search an array using a particular json object in a json file.
This is my json file.
{
"data": [
{
"QueryID": "203972",
"Query_Ref_No": "2019_06749",
"Description": "cannot access files",
"Location": "NULL"
},
{
"QueryID": "203973",
"Query_Ref_No": "2019_06751",
"Description": "cannot access files",
"Location": "NULL"
}
}
Below is my .html code for search. Here , i have used ion-searchbar which will take input and search through the json data and filters the array with the matched result.
<ion-searchbar
animated
icon="search"
inputmode="numeric"
showCancelButton="never"
autocomplete="on"
autocorrect="on"
(ionInput)="filterItems($event)"
(ionCancel)="onCancel()"
placeholder="Enter Request No">
</ion-searchbar>
Below is my .ts file. Here, filterItems(event) function will be called when user enters into searchbar.
I have used function searchData() to get whole json data from json file.
Now I want to filter data on the basis of QUERY_REF_NO.
import { HttpClient } from '#angular/common/http';
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
#Component({
selector: 'app-connect-to-solve-details',
templateUrl: './connect-to-solve-details.component.html',
styleUrls: ['./connect-to-solve-details.component.scss'],
})
export class ConnectToSolveDetailsComponent implements OnInit {
constructor(public router: Router, private http: HttpClient, private c2s: ConnectToSolveService) { }
response: any = []
rev: any = []
id: any
searchdata: any[]
items: any[]
itemsarray: any[]
result: any = []
searchData()
{
this.http.get("/assets/data/C2S/concern_status.json").subscribe((searchdata: any) => {
this.searchdata = searchdata.data;
this.items = this.searchdata;
//console.log(this.searchdata)
console.log(this.items)
})
//return this.response
}
filterItems(event)
{
this.searchData();
const val = event.target.value;
if(val && val.trim() !== '')
{
this.itemsarray = this.items.filter((item) => (this.items.values["Query_Ref_No"].indexOf(val) > -1))
console.log(this.itemsarray)
}
else{
//this.isItemAvailable = false;
}
//console.log(event)
}
}
I am getting error as: ERROR TypeError: Cannot read property 'filter' of undefined
It would be of great help if anyone would tell how to search this.
Thanks in advance.
You can have searchData return the promise and await it inside the filterItems function.
searchData() {
return this.http
.get("/assets/data/C2S/concern_status.json").subscribe()
}
async filterItems(event) {
try {
const response = await this.searchData();
this.searchData = response;
this.items = response.data;
const val = event.target.value;
if(val && val.trim() !== '') {
this.itemsarray = this.items.filter((item) => items["Query_Ref_No"].indexOf(val) > -1)
console.log(this.itemsarray)
}
}
catch (error) {
console.log(error);
}
}

Show Excel File Contents as HTML Table Angular

I am trying to import an Excel File and show it's contents as a table within the web-app
What I have so far:
read-excel.component.ts
import { Component, ElementRef, ViewChild, OnInit, Output } from '#angular/core';
import * as xlsx from 'xlsx';
const { read, utils: { sheet_to_json } } = xlsx;
#Component({
selector: 'app-read-excel',
templateUrl: './read-excel.component.html',
styleUrls: ['./read-excel.component.css']
})
export class ReadExcelComponent implements OnInit {
constructor() {}
ngOnInit () {
}
$mport(data: any, options: xlsx.ParsingOptions): any[][] {
const workBook: xlsx.WorkBook = read(data, options)
const workSheet: xlsx.WorkSheet = workBook.Sheets[workBook.SheetNames[0]]
return sheet_to_json(workSheet, {header : 1, raw: true})
}
}
and in my read-excel.component.html
<div>
<h2> Read Excel Files</h2>
<input type="file" id="input" (change)="$mport()">
<div id='result-table'></div>
<pre id='result'></pre>
</div>
however, when I import the file, I am met with the error Error: Cannot read property 'slice' of undefined in the console
Try with this stackblitz example
import * as XLSX from 'xlsx';
onFileChange(evt: any) {
/* wire up file reader */
const target: DataTransfer = <DataTransfer>(evt.target);
if (target.files.length !== 1) throw new Error('Cannot use multiple files');
const reader: FileReader = new FileReader();
reader.onload = (e: any) => {
/* read workbook */
const bstr: string = e.target.result;
const wb: XLSX.WorkBook = XLSX.read(bstr, { type: 'binary' });
/* grab first sheet */
const wsname: string = wb.SheetNames[0];
const ws: XLSX.WorkSheet = wb.Sheets[wsname];
/* save data */
this.data = <AOA>(XLSX.utils.sheet_to_json(ws, { header: 1 }));
console.log(this.data);
};
reader.readAsBinaryString(target.files[0]);
}
export(): void {
/* generate worksheet */
const ws: XLSX.WorkSheet = XLSX.utils.aoa_to_sheet(this.data);
/* generate workbook and add the worksheet */
const wb: XLSX.WorkBook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
/* save to file */
XLSX.writeFile(wb, this.fileName);
}

Parsing JSON Data working only for template(HTML) but not for Component Class(Typescript)

I would like to parse a json file to use, and extract data.
I don't know why the data extracted from my code work only for my html, but is empty for my typescript code...
json file to parse :
[
{
"appleWatch": "generation_3",
"bracelets": ["model_1","model_2","model_3"]
},
{
"appleWatch": "generation_4",
"bracelets": ["model_1","model_4","model_5"]
}
]
Typescript of my component:
export class AppleKitComponent implements OnInit {
constructor(private httpService: HttpClient) {}
arrAppleWatch: AppleWatchModel[] = [];
selectedWatch: AppleWatchModel = null;
url = '../../assets/json/appleKit.json';
ngOnInit() {
this.arrAppleWatch = this.parseAppleWatchData();
console.log(this.arrAppleWatch.toString() + 'test');
}
parseAppleWatchData() {
this.httpService.get('../../assets/json/appleKit.json').subscribe(
data => {
this.arrAppleWatch = data as AppleWatchModel[]; // FILL THE ARRAY WITH DATA.
},
(err: HttpErrorResponse) => {
console.log(err.message);
}
);
return this.arrAppleWatch;
}
}
My appleWatch model :
export class AppleWatchModel {
constructor(
public watch: string,
public bracelets?: string[],
public bracelet?: string
) {
}
}
HTML:
{{arrAppleWatch |json }}
My log should output :
[ { "appleWatch": "generation_3", "bracelets": [ "model_1", "model_2", "model_3" ] }, { "appleWatch": "generation_4", "bracelets": [ "model_1", "model_4", "model_5" ] } ]
but it just prints an empty string.
My html work and show the array :
[ { "appleWatch": "generation_3", "bracelets": [ "model_1", "model_2", "model_3" ] }, { "appleWatch": "generation_4", "bracelets": [ "model_1", "model_4", "model_5" ] } ]
There are a few issues with your implementation.
The httpService.get call call would be an async call. So it won't give you the data instantly. But you're trying to access it instantly. Hence you're not getting it in the Component Class.
Give this a try:
import { Component } from '#angular/core';
import { HttpClient, HttpErrorResponse } from '#angular/common/http';
export interface AppleWatchModel {
watch: string;
bracelets?: string[];
bracelet?: string;
};
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private httpService: HttpClient) {
}
arrAppleWatch: AppleWatchModel[] = [];
selectedWatch: AppleWatchModel = null;
ngOnInit() {
this.parseAppleWatchData()
.subscribe(res => {
this.arrAppleWatch = res;
console.log('test: ', this.arrAppleWatch);
});
}
parseAppleWatchData() {
return this.httpService.get<AppleWatchModel[]>('/assets/appleKit.json');
}
}
Here, we're returning an Observable<AppleWatchModel[]> from parseAppleWatchData. So we can subscribe to it in the ngOnInit to get the actual data.
Here's a Working Sample StackBlitz for your ref.
Your output is empty because you don't take the asynchronous nature of http requests into account. parseAppleWatchData is returned with the original arrAppleWatch value (which is []) before the http response is received. If you add some logs you will see B comes before A. You can also remove the return value.
export class AppleKitComponent implements OnInit {
constructor(private httpService: HttpClient) {
}
arrAppleWatch: AppleWatchModel [] = [];
selectedWatch: AppleWatchModel = null;
url = '../../assets/json/appleKit.json';
ngOnInit() {
this.parseAppleWatchData();
log('B', this.arrAppleWatch);
}
parseAppleWatchData() {
this.httpService.get('../../assets/json/appleKit.json').subscribe(
data => {
this.arrAppleWatch = data as AppleWatchModel []; // FILL THE ARRAY WITH DATA.
console.log('A', data);
},
(err: HttpErrorResponse) => {
console.log(err.message);
}
);
}

How to bind rowdata of ag-grid inside gridoption using a httpservice

I am using ag-grid license edition and want to bring record set to the grid using a service. I am using Ag-Grid gridoption property and initializing rowdata
in the constructor of the component.ts class. But the data is not rendering. No error either. Please have a look of my component.ts class.
Please note: the web api is returning the json data correctly and the service in Angular is tested sucessfully without Ag-Grid
import {Component, OnInit} from "#angular/core";
import {GridOptions} from "ag-grid";
import {RedComponentComponent} from "../red-component/red-component.component";
import { person } from "../Shared/models/person.model";
import {personservice} from '../service/person.service';
#Component({
selector: 'app-my-grid-application',
templateUrl: './my-grid-application.component.html'
})
export class MyGridApplicationComponent implements OnInit{
private gridOptions: GridOptions;
private persons: person[];
constructor(private personservice: personservice) {
this.gridOptions = <GridOptions>{};
this.gridOptions.columnDefs = [
{
headerName: "ID",
field: "PersonId",
width: 100
},
{
headerName: "Name",
field: "PersonNm",
cellRendererFramework: RedComponentComponent,
width: 100
},
{
headerName: "Email",
field: "PersonEmail",
cellRendererFramework: RedComponentComponent,
width: 100
}
];
this.gridOptions.rowData = this.persons
}
ngOnInit() {
this.personservice.findAll().subscribe(
persons => {
this.persons = persons
},
error => {
console.log(error);
}
)
}
}
Instead of providing columnDefs and rowData with gridOptions, try providing them directly like this.
<ag-grid-angular
[gridOptions]="gridOptions"
[rowData]="rowData"
[columnDefs]="columnDefs"
>
</ag-grid-angular>
Also, declare columnDefs and rowData as component variables, and then assign them after getting the response.
rows: any[] = [];
columnDefs: ColDef[];
constructor(private personservice: personservice) {
this.gridOptions = <GridOptions>{};
this.columnDefs = [
// your column definition goes here
];
}
ngOnInit() {
this.personservice.findAll().subscribe(
persons => {
this.rows = persons
},
error => console.log(error)
)
}
Let me know if you face any issue after this.

Reading content of json file in ionic app

I'm trying to build an app with ionic that reads data from a local `.json' file and uses this data to fill a page. But I'm already struggling with importing the file into the page. What I currently have is:
import { Component } from "#angular/core";
interface Entry {
name: string,
telephone: string
}
interface EntryList {
entryList: Array<Entry>;
}
#Component({
selector: 'page-list',
templateUrl: 'list.html'
})
export class ListPage {
entryList: EntryList;
constructor() {
this.load_entries();
};
load_entries () {
this.entryList = JSON.parse(
// ?
)
};
}
The .json file contains entries like:
[
{"name": "Person A","telephone": "1234"},
{"name": "Person B","telephone": "12345"}
]
I don't know how to proceed from here on. What's the right way to get my data into the app?
Please try this:
constructor(public http: HttpClient) {
this.load_entries();
};
load_entries(filePath: string) { //filePath: 'assets/test.json'
this.http
.get(filePath)
.subscribe((data) => {
console.log(data);
});
}
Of course, you have to import HttpClient first.
import { HttpClient } from '#angular/common/http';