2 * # ============LICENSE_START=======================================================
3 * # Copyright (c) 2020 AT&T Intellectual Property. All rights reserved.
4 * # ================================================================================
5 * # Licensed under the Apache License, Version 2.0 (the "License");
6 * # you may not use this file except in compliance with the License.
7 * # You may obtain a copy of the License at
9 * # http://www.apache.org/licenses/LICENSE-2.0
11 * # Unless required by applicable law or agreed to in writing, software
12 * # distributed under the License is distributed on an "AS IS" BASIS,
13 * # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * # See the License for the specific language governing permissions and
15 * # limitations under the License.
16 * # ============LICENSE_END=========================================================
19 import { Injectable } from '@angular/core';
20 import * as saveAs from 'file-saver';
25 export class DownloadService {
29 /* * * * Download json file * * * */
30 downloadJSON(content, fileName){
31 let file = new Blob([JSON.stringify(content)], { type: 'text;charset=utf-8' });
32 let name: string = `${fileName}.json`
36 /* * * * Export ms instance table to excel or csv * * * */
37 exportTableData(exportTo, downloadElements, arrHeader) {
38 if (exportTo === "excel") {
39 import("xlsx").then(xlsx => {
40 const worksheet = xlsx.utils.json_to_sheet(downloadElements);
41 const workbook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
42 const excelBuffer: any = xlsx.write(workbook, { bookType: 'xlsx', type: 'array' });
43 this.saveAsExcelFile(excelBuffer, "Table_Data");
45 } else if (exportTo === "csv") {
46 let csvData = this.convertToCSV(downloadElements, arrHeader)
47 var blob = new Blob([csvData], { type: 'text/csv' })
48 saveAs(blob, "Table_Data.csv");
51 saveAsExcelFile(buffer: any, fileName: string): void {
52 import("file-saver").then(FileSaver => {
53 let EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
54 let EXCEL_EXTENSION = '.xlsx';
55 const data: Blob = new Blob([buffer], {
58 FileSaver.saveAs(data, fileName + '_export_' + new Date().getTime() + EXCEL_EXTENSION);
61 convertToCSV(objArray, headerList) {
62 let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
65 for (let index in headerList) {
66 row += headerList[index] + ',';
68 row = row.slice(0, -1);
70 for (let i = 0; i < array.length; i++) {
72 for (let index in headerList) {
73 let head = headerList[index];
74 if (array[i][head] === null || array[i][head] === undefined) {
77 if (head === "Labels" && array[i][head].length > 1) { line += '[' + array[i][head].join('] [') + '],'; }
78 else { line += array[i][head] + ','; }