How to Convert JSON to Excel in JavaScript?
Last Updated :
09 Sep, 2024
It is often necessary to export or download JSON data in the form of Excel spreadsheets when developing web applications, any web developer would be able to go through this article as it provides a useful function of converting JSON files to Excel format using SheetsJS through JavaScript.
These are the following ways:
Using SheetJS
(xlsx)
SheetJS is one of those libraries, which specializes in all the operations such as reading, writing, or modifying the files containing spreadsheets, the library includes the support of a number of different formats including the Excel format (XLSX).
You can also install library via npm:
npm install xlsx
Alternatively you can also include the library directly in your HTML:
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
Example: This example shows the use of SheetJs to convert JSON to Excel.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>Convert JSON to Excel</title>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js">
</script>
</head>
<body>
<h1>GeeksForGeeks</h1>
<h5>Approach 1: Using SheetJS (xlsx)</h5>
<button id="export-btn">Export JSON to Excel</button>
<script>
// Sample JSON data
const jsonData = [
{ "Name": "Pankaj Bind", "Age": 21, "Country": "India" },
{ "Name": "Sandeep Singh", "Age": 30, "Country": "Canada" },
{ "Name": "Vivek Kumar", "Age": 22, "Country": "UK" }
];
// Function to export JSON data to Excel
function exportJsonToExcel() {
// Create a new workbook
const workbook = XLSX.utils.book_new();
// Convert JSON data to a worksheet
const worksheet = XLSX.utils.json_to_sheet(jsonData);
// Append the worksheet to the workbook
XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
// Export the workbook as an Excel file
XLSX.writeFile(workbook, "data.xlsx");
}
// Event listener for the export button
document.getElementById("export-btn").addEventListener("click", exportJsonToExcel);
</script>
</body>
</html>
Output:
Using ExcelJS
ExcelJS is also a powerful library which provides ability to create new Excel spreadsheets or modify existing ones from within JavaScript and apply some style.
You can also install library via npm:
npm install exceljs
Alternatively you can also include library directly in your HTML:
<script src="https://cdnjs.cloudflare.com/ajax/libs/exceljs/4.3.0/exceljs.min.js"></script>
Example: This example shows the use of ExcelJS to convert JSON to Excel.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>Convert JSON to Excel using ExcelJS</title>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/exceljs/4.3.0/exceljs.min.js"></script>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
</head>
<body>
<h1>GeeksForGeeks</h1>
<h5>Approach 2: Using ExcelJS</h5>
<button id="export-btn">Export JSON to Excel</button>
<script>
// Sample JSON data
const jsonData = [
{ "Name": "Pankaj Bind", "Age": 21, "Country": "India" },
{ "Name": "Sandeep Singh", "Age": 30, "Country": "Canada" },
{ "Name": "Vivek Kumar", "Age": 22, "Country": "UK" }
];
// Function to export JSON to Excel using ExcelJS
async function exportJsonToExcel() {
// Create a new workbook
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet("Sheet1");
// Add column headers
worksheet.columns = [
{ header: "Name", key: "name" },
{ header: "Age", key: "age" },
{ header: "Country", key: "country" }
];
// Add rows to the worksheet
jsonData.forEach(data => {
worksheet.addRow({
name: data.Name,
age: data.Age,
country: data.Country
});
});
// Export the workbook to Excel file
const buffer = await workbook.xlsx.writeBuffer();
const blob = new Blob([buffer],
{ type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
saveAs(blob, "data.xlsx");
}
document.getElementById("export-btn").addEventListener("click", exportJsonToExcel);
</script>
</body>
</html>
Output:
Converting the JSON into a CSV file format and then providing this as a downloadable file which can be opened as excel exported well this approach works too, this is a simple solution if you don’t want all the overhead that comes with using the Microsoft excel file format.
You can also install library via npm:
npm install file-saver
Alternatively you can also include library directly in your HTML:
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
Example: This example shows the use of FileSaver.js to convert JSON to Excel.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>Convert JSON to CSV</title>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js">
</script>
</head>
<body>
<h1>GeeksForGeeks</h1>
<h5>Approach 3: Using FileSaver.js with CSV Format</h5>
<button id="export-btn">Export JSON to CSV</button>
<script>
// Sample JSON data
const jsonData = [
{ "Name": "Pankaj Bind", "Age": 21, "Country": "India" },
{ "Name": "Sandeep Singh", "Age": 30, "Country": "Canada" },
{ "Name": "Vivek Kumar", "Age": 22, "Country": "UK" }
];
// Function to convert JSON to CSV
function jsonToCsv(jsonData) {
const headers = Object.keys(jsonData[0]).join(",") + "\n";
const rows = jsonData.map(obj => Object.values(obj).join(",")).join("\n");
return headers + rows;
}
// Function to export CSV using FileSaver.js
function exportJsonToCsv() {
const csvData = jsonToCsv(jsonData);
const blob = new Blob([csvData], { type: "text/csv;charset=utf-8;" });
saveAs(blob, "data.csv");
}
document.getElementById("export-btn")
.addEventListener("click", exportJsonToCsv);
</script>
</body>
</html>
Output:
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read