Reputation: 327
I have created my Data table from the angular 2 website. Now I want to export my json data to PDF,excel using angular 2 framework.
Kindly give me suggestion how can I achieve that or any link if you have.
Regards
Upvotes: 7
Views: 17628
Reputation: 1
//Excel
import * as XLSX from 'xlsx';
import * as FileSaver from 'file-saver';
export class YourComponent {
jsonData: any[] = [
{ id: 1, name: 'A', age: 28 },
{ id: 2, name: 'B', age: 34 },
{ id: 3, name: 'C', age: 22 }
];
exportToExcel(): void {
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(this.jsonData);
const workbook: XLSX.WorkBook = {
Sheets: { 'DataSheet': worksheet },
SheetNames: ['DataSheet']
};
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
this.saveAsExcelFile(excelBuffer, 'DataExport');
}
private saveAsExcelFile(buffer: any, fileName: string): void {
const data: Blob = new Blob([buffer], { type: 'application/octet-stream' });
FileSaver.saveAs(data, `${fileName}.xlsx`);
}
}
//PDF
import jsPDF from 'jspdf';
import 'jspdf-autotable';
export class YourComponent {
jsonData: any[] = [
{ id: 1, name: 'A', age: 28 },
{ id: 2, name: 'B', age: 34 },
{ id: 3, name: 'C', age: 22 }
];
exportToPDF(): void {
const doc = new jsPDF();
const columns = ['ID', 'Name', 'Age'];
const rows = this.jsonData.map(item => [item.id, item.name, item.age]);
doc.text('Exported Data', 14, 16);
(doc as any).autoTable({
head: [columns],
body: rows,
startY: 20,
});
doc.save('DataExport.pdf');
}
}
Upvotes: -1
Reputation: 5640
I can answer your question partially so that you can export your JSON
data to excel
. You can use XLSX library for Angular 2+
.
Assuming your JSON
data will be something like what assigned to readyToExport
and hence it is shown how to export your JSON
data.
public export() {
const readyToExport = [
{id: 1, name: 'a', address: 'x'},
{id: 2, name: 'b', address: 'y'},
{id: 3, name: 'c', address: 'z'}
];
const workBook = XLSX.utils.book_new(); // create a new blank book
const workSheet = XLSX.utils.json_to_sheet(readyToExport);
XLSX.utils.book_append_sheet(workBook, workSheet, 'data'); // add the worksheet to the book
XLSX.writeFile(workBook, 'temp.xlsx'); // initiate a file download in browser
}
Upvotes: 0
Reputation: 416
I was finally used this one:
function downloadExcelFile(ev) {
connectionService.getExcelExport(function (response) {
if (response.status == 200) {
/**
* Export data to csv file
*/
let blob = new Blob([response.data], {type: 'text/csv'});
let filename = `export.csv`;
if(window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
}
else{
let elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(blob);
elem.download = filename;
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);
}
console.log(`export excel file is successful.`);
}
})
}
Upvotes: 0
Reputation: 9638
Maybe you should look for how to export your data-table
to a JSON
format object then there is plenty of examples how to convert a JSON to PDF/CSV and could be used in native JavaScript
or TypeScript
.
Those links may help you:
Converting json to pdf using js frameworks and
http://jsfiddle.net/hybrid13i/JXrwM/
Upvotes: 0
Reputation: 7
(function () {
'use strict';
angular.module('ngJsonExportExcel', [])
.directive('ngJsonExportExcel', function () {
return {
restrict: 'AE',
scope: {
data : '=',
filename: '=?',
reportFields: '=',
separator: '@'
},
link: function (scope, element) {
scope.filename = !!scope.filename ? scope.filename : 'SalesReport';
var fields = [];
var header = [];
var separator = scope.separator || ',';
angular.forEach(scope.reportFields, function(field, key) {
if(!field || !key) {
throw new Error('error json report fields');
}
fields.push(key);
header.push(field);
});
element.bind('click', function() {
var bodyData = _bodyData();
var strData = _convertToExcel(bodyData);
var blob = new Blob([strData], {type: "text/plain;charset=utf-8"});
return saveAs(blob, [scope.filename + '.csv']);
});
function _bodyData() {
var data = scope.data;
var body = "";
angular.forEach(data, function(dataItem) {
var rowItems = [];
angular.forEach(fields, function(field) {
if(field.indexOf('.')) {
field = field.split(".");
var curItem = dataItem;
// deep access to obect property
angular.forEach(field, function(prop){
if (curItem !== null && curItem !== undefined) {
curItem = curItem[prop];
}
});
data = curItem;
}
else {
data = dataItem[field];
}
var fieldValue = data !== null ? data : ' ';
if (fieldValue !== undefined && angular.isObject(fieldValue)) {
fieldValue = _objectToString(fieldValue);
}
if(typeof fieldValue == 'string') {
rowItems.push('"' + fieldValue.replace(/"/g, '""') + '"');
} else {
rowItems.push(fieldValue);
}
});
body += rowItems.join(separator) + '\n';
});
return body;
}
function _convertToExcel(body) {
return header.join(separator) + '\n' + body;
}
function _objectToString(object) {
var output = '';
angular.forEach(object, function(value, key) {
output += key + ':' + value + ' ';
});
return '"' + output + '"';
}
}
};
});
})();
Upvotes: -1