Excel files store data in rows and columns, while JSON represents data as key-value pairs. Converting Excel to JSON in JavaScript makes spreadsheet data easier to process, display, and integrate into web applications.
- Data Conversion: Converts spreadsheet rows into JSON objects using column headers as keys.
- Data Processing: Makes spreadsheet data easier to manipulate with JavaScript.
- Data Export: Allows converted data to be displayed or downloaded as a JSON file.
Convert an Excel File to JSON and Download It
The following example allows users to select an Excel file, convert its rows into JSON objects, preview the result, and download the generated JSON file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Excel to JSON Converter</title>
</head>
<body>
<h2>Excel to JSON Converter</h2>
<input type="file" id="excel_file" accept=".xlsx, .xls">
<button id="convert_btn">Convert to JSON</button>
<button id="download_btn" disabled>Download JSON</button>
<pre id="json_data"></pre>
<script src="https://unpkg.com/read-excel-file@5.8.8/bundle/read-excel-file.min.js"></script>
<script>
const fileInput = document.getElementById("excel_file");
const output = document.getElementById("json_data");
const downloadButton = document.getElementById("download_btn");
let jsonData = "";
document.getElementById("convert_btn").addEventListener("click", async () => {
const file = fileInput.files[0];
if (!file) {
output.textContent = "Please select an Excel file.";
return;
}
try {
const rows = await readXlsxFile(file);
if (rows.length === 0) {
output.textContent = "The Excel file is empty.";
return;
}
const headers = rows[0].map(header =>
String(header ?? "").trim()
);
const records = rows.slice(1).map(row => {
const record = {};
headers.forEach((header, index) => {
if (header) {
record[header] = row[index] ?? null;
}
});
return record;
});
jsonData = JSON.stringify(records, null, 2);
output.textContent = jsonData;
downloadButton.disabled = false;
} catch (error) {
jsonData = "";
downloadButton.disabled = true;
output.textContent = "Unable to read the Excel file.";
console.error(error);
}
});
downloadButton.addEventListener("click", () => {
if (!jsonData) return;
const blob = new Blob([jsonData], {
type: "application/json"
});
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = "excel_to_json.json";
link.click();
URL.revokeObjectURL(url);
});
</script>
</body>
</html>
Output: