Exporting JSON Data to Excel and PDF in Angular : A How-To Guide

Rijul Dahiya
4 min readMar 30, 2023

--

Photo by Luke Chesser on Unsplash

In modern web development, data visualization and export capabilities are essential for most applications. Being able to export data to various formats, such as Excel and PDF, allows users to further analyze and manipulate data beyond the scope of the application.

While there are many libraries available to accomplish this task, not all projects can use them due to technical or licensing limitations. In this guide, we’ll show you how to export JSON data to Excel and PDF in Angular without using any external libraries. By the end of this tutorial, you’ll have a better understanding of how to implement these features in your own Angular projects.

If you don’t want to use any libraries, you can write your own code to export JSON to CSV, Excel, and PDF. Here’s an example of how you can export JSON data to CSV without using any external libraries:

import { Component } from '@angular/core';

@Component({
selector: 'app-export-csv',
template: `
<button (click)="exportToCsv()">Export to CSV</button>
`
})
export class ExportCsvComponent {
jsonResponse = '[{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]';

exportToCsv() {
const data = JSON.parse(this.jsonResponse);
const columns = this.getColumns(data);
const csvData = this.convertToCsv(data, columns);
this.downloadFile(csvData, 'data.csv', 'text/csv');
}

getColumns(data: any[]): string[] {
const columns = [];
data.forEach(row => {
Object.keys(row).forEach(col => {
if (!columns.includes(col)) {
columns.push(col);
}
});
});
return columns;
}

convertToCsv(data: any[], columns: string[]): string {
let csv = '';
csv += columns.join(',') + '\n';
data.forEach(row => {
const values = [];
columns.forEach(col => {
values.push(row[col] || '');
});
csv += values.join(',') + '\n';
});
return csv;
}

downloadFile(data: string, filename: string, type: string) {
const blob = new Blob([data], { type: type });
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
} else {
const link = document.createElement('a');
link.setAttribute('href', URL.createObjectURL(blob));
link.setAttribute('download', filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}

In this example, the getColumns() method is used to get the list of column names from the JSON data. We iterate over each row in the data and check if each column exists in the columns array. If not, we add it to the array.

The convertToCsv() method is used to convert the JSON data to CSV format. We start by adding the column names to the CSV file, followed by the data rows. For each row, we iterate over each column and add the corresponding value to the CSV file. If a value is missing, we add an empty string instead.

Finally, the downloadFile() method is used to download the CSV file. We create a Blob object containing the CSV data and use the URL.createObjectURL() method to create a URL that can be used to download the file. We create a link element with the download attribute set to the file name and simulate a click on the link to trigger the download.

Note that this example only exports to CSV. You would need to write additional code to export to Excel and PDF formats. The general approach would be similar, but the implementation details would be different.

For Excel, we can use the xlsx library that is built into modern browsers to generate an Excel file from the JSON data. Here's an example of how to modify the code from the previous example to export the JSON data to Excel:

import { Component } from '@angular/core';

@Component({
selector: 'app-export-excel',
template: `
<button (click)="exportToExcel()">Export to Excel</button>
`
})
export class ExportExcelComponent {
jsonResponse = '[{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]';

exportToExcel() {
const data = JSON.parse(this.jsonResponse);
const columns = this.getColumns(data);
const worksheet = XLSX.utils.json_to_sheet(data, { header: columns });
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
XLSX.writeFile(workbook, 'data.xlsx');
}

getColumns(data: any[]): string[] {
const columns = [];
data.forEach(row => {
Object.keys(row).forEach(col => {
if (!columns.includes(col)) {
columns.push(col);
}
});
});
return columns;
}
}

In this example, we use the json_to_sheet() method from the xlsx library to convert the JSON data to an Excel worksheet. We pass in an options object that specifies the column headers to use ({ header: columns }). We then create a new workbook and append the worksheet to it using the book_append_sheet() method. Finally, we use the writeFile() method to download the Excel file.

For PDF, we can use the jsPDF library to generate a PDF file from the JSON data. Here's an example of how to modify the code from the previous example to export the JSON data to PDF:

import { Component } from '@angular/core';
import * as jsPDF from 'jspdf';

@Component({
selector: 'app-export-pdf',
template: `
<button (click)="exportToPdf()">Export to PDF</button>
`
})
export class ExportPdfComponent {
jsonResponse = '[{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]';

exportToPdf() {
const data = JSON.parse(this.jsonResponse);
const columns = this.getColumns(data);
const rows = this.getRows(data, columns);
const doc = new jsPDF();
doc.autoTable({
head: [columns],
body: rows
});
doc.save('data.pdf');
}

getColumns(data: any[]): string[] {
const columns = [];
data.forEach(row => {
Object.keys(row).forEach(col => {
if (!columns.includes(col)) {
columns.push(col);
}
});
});
return columns;
}

getRows(data: any[], columns: string[]): any[] {
const rows = [];
data.forEach(row => {
const values = [];
columns.forEach(col => {
values.push(row[col] || '');
});
rows.push(values);
});
return rows;
}
}

In this example, we use the autoTable() method from the jsPDF library to generate a table in the PDF file. We pass in an options object that specifies the column headers ({ head: [columns] }) and the data rows ({ body: rows }).

In conclusion, exporting JSON data to Excel and PDF is a valuable skill for any Angular developer to have. By following the techniques demonstrated in this guide, you can easily implement this feature in your Angular applications without relying on external libraries. By leveraging the built-in functionality of modern browsers and utilizing the jsPDF library, you can provide your users with a seamless and efficient data export experience. With these techniques in your arsenal, you'll be well-equipped to tackle any data export needs that arise in your Angular projects.

--

--

Rijul Dahiya

Founder @ TenderEarth | SDE @ Groupon | Follow me to learn more on the cultural dimensions of technology