24.07.2021 a las 18:31
Aprende a exportar un JSON con TypeScript o JavaScript sin librería de terceros.
A continuación te diré como exportar un JSON a CSV sin utilizar librerías de terceros, es bastante fácil.
Un fichero CSV es un archivo de texto plano usado para representar datos en forma de tabla. Para separar columnas yo uso el ; y las filas las separo por saltos de línea.
Necesitaremos dos funciones para exportar el JSON a CSV, un primer método de convertir un formato en otro, y un segundo método para descargar el archivo.
ConvertToCSV(objArray:any, headerList:string[]) { let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray; let str = ''; let row:string = ''; for (let index in headerList) { row += headerList[index] + ';'; } row = row.slice(0, -1); str += row + ' '; for (let i = 0; i < array.length; i++) { let line = ''; for (let index in headerList) { let head = headerList[index]; line += array[i][head] + ';'; } str += line + ' '; } return str; }
downloadFile(data:unknown, columnHeaders:string[], filename = 'data') { let blob = new Blob(['' + csvData], { type: 'text/csv;charset=utf-8;', }); let dwldLink = document.createElement('a'); let url = URL.createObjectURL(blob); let isSafariBrowser = navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1; if (isSafariBrowser) { dwldLink.setAttribute('target', '_blank'); } dwldLink.setAttribute('href', url); dwldLink.setAttribute('download', filename + '.csv'); dwldLink.style.visibility = 'hidden'; document.body.appendChild(dwldLink); dwldLink.click(); document.body.removeChild(dwldLink); }
Para usarlo en Angular, me creo un servicio el cual inyecto en el componente que necesito. De forma que llamando al método downloadFile del servicio y pasándole como argumentos el json y los encabezados descargaría el fichero CSV. Como opcional puedes pasar el nombre del fichero como tercer argumento.
El servicio sería:
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class FileExportService { constructor() {} public downloadFile(data:unknown, columnHeaders:string[], filename = 'data') { let csvData = this.ConvertToCSV(data, columnHeaders); let blob = new Blob(['' + csvData], { type: 'text/csv;charset=utf-8;', }); let dwldLink = document.createElement('a'); let url = URL.createObjectURL(blob); let isSafariBrowser = navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1; if (isSafariBrowser) { dwldLink.setAttribute('target', '_blank'); } dwldLink.setAttribute('href', url); dwldLink.setAttribute('download', filename + '.csv'); dwldLink.style.visibility = 'hidden'; document.body.appendChild(dwldLink); dwldLink.click(); document.body.removeChild(dwldLink); } private ConvertToCSV(objArray:any, headerList:string[]) { let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray; let str = ''; let row:string = ''; for (let index in headerList) { row += headerList[index] + ';'; } row = row.slice(0, -1); str += row + ' '; for (let i = 0; i < array.length; i++) { let line = ''; for (let index in headerList) { let head = headerList[index]; line += array[i][head] + ';'; } str += line + ' '; } return str; } }
No explica paso por paso qué hace cada método porque es bastante sencillo, no obstante si necesitas ayuda me puedes contactar.
Hasta luego 🖖
Software
IoT
Digitalización
Aplicaciones móviles
Consultoría