quick-excel-json
Version:
Convert Excel (.xlsx, .xls, .csv) files to JSON easily. Fast, lightweight, and perfect for React, Node.js, and web applications. Supports SheetJS and ExcelJS and a simple npm package to convert JSON data to an Excel (.xlsx, .xls) file using SheetJS (xlsx)
50 lines (44 loc) • 1.9 kB
JavaScript
import * as XLSX from 'xlsx';
// excel to json
export const fileHandler = file => {
return new Promise((resolve, reject) => {
if (!file) {
reject("No file provided");
return;
}
const reader = new FileReader();
reader.onload = (e) => {
try {
const data = e.target.result;
const workbook = XLSX.read(data, { type: "array" });
const sheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[sheetName];
const json = XLSX.utils.sheet_to_json(worksheet, { raw: false });
resolve(JSON.stringify(json, null, 2)); // JSON natijani qaytaramiz
} catch (error) {
reject(error);
}
};
reader.onerror = () => reject("File reading error");
reader.readAsArrayBuffer(file);
});
}
// json to excel
export const handleExportHandler = (jsonData) => {
if (jsonData instanceof File) { // checks if it is a file.
const reader = new FileReader();
reader.onload = (e) => {
const data = JSON.parse(e.target.result);
const ws = XLSX.utils.json_to_sheet(data); // converting json data to excel
const wb = XLSX.utils.book_new(); // create excel file
XLSX.utils.book_append_sheet(wb, ws, "Sheet1"); // create excel file
XLSX.writeFile(wb, "exported_data.xlsx"); // download file
};
reader.readAsText(jsonData);
} else {
const ws = XLSX.utils.json_to_sheet(jsonData); // converting json data to excel
const wb = XLSX.utils.book_new(); // create excel file
XLSX.utils.book_append_sheet(wb, ws, "Sheet1"); // create excel file
XLSX.writeFile(wb, "exported_data.xlsx"); // download file
}
};