In web development, dealing with data in various formats is a common task. One frequent scenario is the need to convert Excel files into a more flexible and accessible format, such as JSON. In this blog post, we’ll explore how to achieve this using JavaScript, with a focus on React.js and Next.js.You can use this code in Vanila.js project also.
Getting Started
To get started, we’ll use the excellent xlsx library, which provides functionality for reading and writing Excel files.
Installing package
Open your code editior & open project folder.Now open terminal on this folder & write this script to install xlsx package.
npm install xlsx
or
yarn add xlsx
The code we’ll be working with is encapsulated in a module named excelToJson.js.
// excelToJson.js
import * as XLSX from "xlsx";
This module contains two essential functions: downloadExcelAsArrayBuffer and convertExcelToJson. Let's break down each step of the process.
Downloading Excel File
The first step is to download the Excel file as an ArrayBuffer. This function uses the fetch API to retrieve the file from a given URL.
// excelToJson.js
import * as XLSX from "xlsx";
//The first step is to download the Excel file as an ArrayBuffer. This function uses the fetch API to retrieve the file from a given URL.
const downloadExcelAsArrayBuffer = async (excelUrl) => {
try {
// Fetch the Excel file
const response = await fetch(excelUrl);
if (!response.ok) {
throw new Error(`Failed to download Excel file. Status: ${response.status}`);
}
// Convert the response to ArrayBuffer
const arrayBuffer = await response.arrayBuffer();
return arrayBuffer;
} catch (error) {
console.error("Error downloading Excel file:", error);
throw error;
}
};
Converting Excel to JSON
The core functionality lies in the convertExcelToJson function. It performs the conversion from Excel to JSON using the xlsx library.
const convertExcelToJson = async (excelUrl) => {
try {
// Download the Excel file as ArrayBuffer
const arrayBuffer = await downloadExcelAsArrayBuffer(excelUrl);
// Convert the Excel buffer to a workbook
const workbook = XLSX.read(arrayBuffer, { type: "array" });
// Get the first sheet
const sheetName = workbook.SheetNames[0];
const sheet = workbook.Sheets[sheetName];
// Convert the sheet data to JSON
const jsonData = XLSX.utils.sheet_to_json(sheet, { header: 1 });
// Map the array to an array of objects
const resultArray = jsonData.map((row) => {
const obj = {};
for (let i = 0; i < jsonData[0].length; i++) {
obj[jsonData[0][i]] = row[i];
}
return obj;
});
return resultArray.slice(1);
} catch (error) {
console.error("Error converting Excel to JSON:", error);
throw error;
}
};
Implementing in React.js/Next.js
To use this functionality in a React.js or Next.js project, simply import the convertExcelToJson function and use it as needed.
import convertExcelToJson from "./path/to/excelToJson";
const YourComponent = async () => {
try {
const jsonData = await convertExcelToJson("your_excel_file_url.xlsx");
console.log(jsonData);
// Now you can use jsonData in your React component
} catch (error) {
// Handle errors
}
};
With this script, you can easily convert downloadable Excel files to JSON in your JavaScript projects. This process is especially handy when dealing with data imports and exports in web applications.
Happy coding!
Top comments (0)